1. Creating Twitter maps
Great job! Now that we've seen how to extract coordinates from Twitter data, we can start looking at how to create maps of tweets within Python. We'll learn how to render maps and how to plot points on those maps.
2. Introducing Basemap
Basemap is a library for plotting two dimensional maps in Python. Basemap is built on top of matplotlib, so much of the functionality that you got out of matplotlib applies maps you create with it. Basemap transforms coordinates into map projections, while matplotlib draws contours, lines, and points.
3. Beginning with Basemap
To create a new Basemap object, we'll first import it from the matplotlib toolkits. We then create a new Basemap object with five arguments. The first is the map projection we want to use. A map projection is the method for which we translate latitudes and longitudes of the Earth -- which is spherical -- onto a two-dimensional plane. Because we will be dealing with latitudes closer to the equator, we'll use the Mercator projection, which is denoted by 'merc'.
We'll then provide coordinates for the lower level and upper right corners of the map. The second and third arguments, `llcrnrlat` and `llcrnrlon` stand for lower left corner latitude and lower left corner longitude, respectively. The same goes for the upper right latitudes and longitudes.
Lastly, we'll make the continents white with the `fillcontinents` method, then draw the coast lines with gray with the `drawcoastlines` method, and draw the national borders with gray using the `drawcountries` method.
4. Plotting points
Now we add points to the map. To do this, we need a list of longitudes and latitudes. In this example, we're going to use the coordinates of capital cities for African countries. We'll first load the dataset. We'll then create the Basemap map. Next, we'll use the `fillcontinents` method, but we'll add a new argument, `zorder`, and set it zero. This ensures that the continents appear behind the points. Lastly, we'll use the `scatter` method and pass it the longitudes, then latitudes, to plot them. We need to let Basemap know that these values are latitudes and longitudes, so we'll set `latlon` equal to True. And we'll make them slightly transparent by setting alpha equal to 0-point-7.
5. Using color
Lastly, say we want to show some feature of a particular location, like whether Arabic is an official language. We can use a variable to denote that status and use a matplotlib to display it. In the `scatter` method, we add the argument `c` and pass it a list of that new variable. We need to also use `cmap` to select the matplotlib colormap we want to use. In the upcoming exercise, we're going to revisit a continuous variable -- Twitter sentiment -- to denote color.
6. Let's practice!
Now let's put some points on the map. We're going to plot tweets from the State of the Union dataset, as well as plot their sentiment.