plotly

Plotly.Figure_Factory.Create_Hexbin_Mapbox

In this article, we will explore how to use the Plotly figure_factory module and Mapbox API to create hexbin plots.

Keep in mind that this may require you to have a Mapbox account and access Token.

Basic Hexbin Plot

The following code shows how to use the figure_factory module to create a basic hexbin plot using the Mapbox API.

from plotly.figure_factory import create_hexbin_mapbox

import plotly.express as px

px.set_mapbox_access_token(open("mapbox.mapbox_token").read())

df = px.data.carshare()

fig = create_hexbin_mapbox(

data_frame=df, lat="centroid_lat", lon="centroid_lon",

nx_hexagon=10, opacity=0.9, labels={"color": "Point Count"},

)

fig.show()

The given example uses the carshare data from Plotly express to create a simple hexbin plot. Ensure to replace the mapbox.mapbox_token with the file containing your Mapbox access token.

Output Figure:

You can change the colorscale by setting a different value to the colorscale_continous_scale parameter as shown in the following:

from plotly.figure_factory import create_hexbin_mapbox

import plotly.express as px

px.set_mapbox_access_token(open("mapbox.mapbox_token").read())

df = px.data.carshare()

fig = create_hexbin_mapbox(

data_frame=df, lat="centroid_lat", lon="centroid_lon",

nx_hexagon=10, opacity=0.9, labels={"color": "Point Count"},

color_continuous_scale='viridis'

)

fig.show()

This sets the colorscale to viridis as shown in the following output:

To customize the opacity of the bins, you can customize the opacity parameter as shown in the following:

fig = create_hexbin_mapbox(

data_frame=df, lat="centroid_lat", lon="centroid_lon",

nx_hexagon=10, opacity=0.5, labels={"color": "Point Count"},

color_continuous_scale='viridis',

)

fig.show()

In this case, the plot uses a .5 opacity as shown in the following:

To display the underlying data within the plot, you can use the show_original_data parameter as follows:

fig = create_hexbin_mapbox(

data_frame=df, lat="centroid_lat", lon="centroid_lon",

nx_hexagon=10, opacity=0.5, labels={"color": "Point Count"},

color_continuous_scale='viridis',

show_original_data=True

)

fig.show()

Output:

Conclusion

In this article, we explored how to use the Plotly figure_factory module and the Mapbox API to create the hexbin plots. Check the docs for more.

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