The world’s leading publication for data science, AI, and ML professionals.

Simplest Way of Creating a Choropleth Map by U.S. States in Python

Use This Code Template to Create the Map Under Two Minutes – No GeoJson Needed

Image by Pixabay (Modified by Author)
Image by Pixabay (Modified by Author)

Choropleth maps are one of the most popular geospatial data visualizations. It is a type of thematic map that uses different shadings in predefined areas on a map to represent geographic characteristics in relation to a metric. It can be plotted on virtually any map and by different geographic areas such as countries, states, counties, zip codes, etc.

Folium is usually my go-to package to create choropleth maps, especially the ones that might need a lot of customizations on flavors and designs. However, a lot of times, we might just need to plot a simple choropleth map by U.S. states (like the example below) and do not want to go through the hassles of using geopandas or importing geojson files to get the job done.

Image by Author
Image by Author

After comparing multiple graphing libraries such as Folium, Plotly, Matplotlib, etc., I found that using Plotly_Express is the simplest and fastest way of creating a beautiful U.S. choropleth map by states. Plotly_Express has built-in U.S. states geometries so there is no need to use any GeoJson file. All you need is just to specify a couple of parameters in a simple code template and you are all set!


Pre-requisite

If you haven’t already done so, you will need to install Plotly_Express by using the following command:

pip install plotly-express

Also, in this post, we are going to use a small sample dataset to create a choropleth map that visualizes the U.S. single-family property prices by state in January 2022.

To download the raw dataset, go to [Redfin](https://www.redfin.com/news/data-center/)’s Data Center, scroll down to the ‘How it Works’ section, and download the region data at the ‘state’ level. This is a free, open dataset that you can download and use for your own purposes with citation to Redfin. We can then use the following code to only select the columns and data we need for plotting the map.

Image by Author
Image by Author

Create a Choropleth Map by U.S. States

Now that our data is ready, let’s see how easy it is to create a choropleth map by U.S. states using Plotly_Express. Below is the code template you can use to plot any choropleth map by U.S. states using Plotly_Express.

import plotly.express as px
fig = px.choropleth(df,
                    locations='state_code', 
                    locationmode="USA-states", 
                    scope="usa",
                    color='Median Sales Price ($)',
                    color_continuous_scale="Viridis_r", 

                    )
fig.show()

The following are a few important parameters you need to specify in the code template:

  • locations: This should be the name of the column that represents the U.S. states in your dataframe. Make sure you provide locations as two-letter state abbreviations.
  • locationmode: To use Plotly_Express’ built-in USA States geometry, you need to set locationmode='USA-states'.
  • scope: This should be specified as ‘usa’.
  • color: This should be the name of the column that represents the metric you want to visualize by state.
  • color_continuous_scale: You can use any of the following named color scales. You can add ‘_r’ to a named color scale to reverses it.
Image by Author
Image by Author

This is basically it! If you want to add a title with some formatting to the map, you can simply add the following code as well:

fig.update_layout(
      title_text = 'Jan 2022 Median Housing Price by State',
      title_font_family="Times New Roman",
      title_font_size = 22,
      title_font_color="black", 
      title_x=0.45, 
         )
Image by Author
Image by Author

Bonus: Create an Animated Choropleth Map by U.S. States

In the example above, we used plotly_express to create a snapshot choropleth map that visualizes the housing prices by states in January 2022. It would be interesting to see how the housing prices by states evolve over time using an animated choropleth map.

The good news is that it is super easy to do it with plotly_express. All you need to do is to make sure you have your time horizon column (in our example: ‘period_begin’) sorted in ascending order (line 9), and then just add the animation_frame parameter in your px.choropleth() code (line 17)!

GIF by Author
GIF by Author

[Plotly](https://plotly.com/python/choropleth-maps/)_Express also has built-in geometries for world maps with countries that are defined in the Natural Earth dataset. According to Plotly’s documentation, to use the built-in countries geometry, you need to provide locations as three-letter ISO country codes. Everything else follows the same code template of the U.S. states choropleth map.

If you need to plot a choropleth map by geographic areas other than U.S. states or world countries, then you will need to use proper GeoJson files to define the corresponding geographic area boundaries, e.g., counties, zip codes, etc. You can use Plotly_Express, Plotly_Go, or Folium to create the map. You can read the following article if you want to learn how to use Folium to create a highly customizable and sophisticated choropleth map.

Folium and Choropleth Map: From Zero to Pro

Thanks for reading! I hope you enjoyed the tutorial and learned something new about geospatial data visualization.


Reference and Data Source

  1. Plotly Documentation: https://plotly.com/python/choropleth-maps/
  2. Data Source: Redfin Monthly Housing Market Data – State Level. This is an open dataset provided by Redfin, __ a national real estate brokerage, that you can download for free and for your own purposes with citation.

You can unlock full access to my writing and the rest of Medium by signing up for Medium membership ($5 per month) through this referral link. By signing up through this link, I will receive a portion of your membership fee at no additional cost to you. Thank you!


Related Articles