plotly

plotly.graph_objects.choropleth

This article will explore creating a Choropleth Map using the Plotly graph_objects module.

Creating World Map With go.Choropleth

We can use the Choropleth class from graph_objects to create a Choropleth Map. To illustrate, consider the following code that uses US exports data to create a Choropleth Map:

import plotly.graph_objects as go
import pandas as pd
import plotly.express as px
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
fig = go.Figure(data=go.Choropleth(
    locations=df['code'],
    z = df['total exports'].astype(float),
    locationmode = 'USA-states',
    colorscale = px.colors.sequential.Plasma,
))
fig.show()

The previous code will create a world map with the data in the dataset highlighted in the following figure:

Setting Map Scope

We can limit the map display scope to only the US by setting the geo_scope parameter as follows:

fig.update_layout(geo_scope='usa')
fig.show()

The resulting figure is shown in the following figure:

Setting Figure Title

We can also use the update_layout() function to set a title for the figure as illustrated in the following code:

fig.update_layout(geo_scope='usa', title_text = "US Agriculture Exports 2011")
fig.show()

Output

World GDP Choropleth Map

Similarly, we can use the Choropleth class to create a world map showing the World GDP as illustrated in the following code:

import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
    locations = df['CODE'],
    z = df['GDP (BILLIONS)'],
    text = df['COUNTRY'],
    colorscale = 'Plasma',
    marker_line_color='darkgray',
    marker_line_width=0.5,
    colorbar_tickprefix = '$',
    colorbar_title = 'GDP<br>Billions US$',
))
fig.show()

Resulting World Map

Conclusion

This article covered the basics of creating Choropleth Maps using the Choropleth class from Plotly graph_objects. We learned how to create a world map, set the map scope, set the figure title, and the world GDP Choropleth Map. For more articles like this, check out Linux Hint to enhance or gain more knowledge.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list