Geographical Plotting
Explore how to create interactive geographical visualizations using Plotly in Python. Understand how to work with choropleth maps, handle geographic datasets, and customize visual elements for US and world maps. Gain practical skills in building text data for hover features and applying various color scales for effective data presentation.
We'll cover the following...
Geographical plotting is usually challenging because of the various formats in the data sets. Plotly provides a way to plot geographical data interactively using its choropleth type.
Note: Matplotlib also provides the extension
basemapfor static geographical plotting.
Write the following code and review it line by line using inline comments.
The following code will show us how we can create geographical plots using Plotly:
The following plot is generated by the code given above:
US map choropleth
Now let’s see an example with some real data on exports. The datasets are available on the Plotly GitHub page. We can pass a link to the dataset and read it directly into a DataFrame. A copy of the dataset (with a few small modifications) is also included in the folder, in case you can’t access the internet. We can read the data from these downloaded .csv files. When using the included .csv files, you don’t need to do the steps to add new columns.
If we look at the DataFrame, we have individual columns for the export of the given products (beef, dairy, veggies, and so on) to each state.
We have to build our text column most of the time, so let’s create a new column that combines this information. Then, we can pass it to the text key that will hover on the plot.
We need to convert the column datatype from float to string first.
Let’s create the data dictionary with some extra marker and color bar arguments. We’ll then create a layout and get our geographical plot.
The following plot is generated by the code given above:
The following are some possible
colorscalevalues you can try:['Greys', 'YlGnBu', 'Greens', 'YlOrRd', 'Bluered', 'RdBu', 'Reds', 'Blues', 'Picnic', 'Rainbow', 'Portland', 'Jet', 'Hot', 'Blackbody', 'Earth', 'Electric', 'Viridis', 'Cividis'].
Note: These values are updated frequently. Please consult the official documentation of Plotly to see the updated list of colorscale values.
World choropleth map
Now let’s see an example with a world map.
Let’s use iplot to print the map.
The following plot is generated by the code given above:
To see everything in action, run the app given below.