Plotly


Plotly is a library that allows you to create interactive plots that you can use in dashboards or websites.

https://plotly.com/python/plotly-express/

Setup

> import plotly.express as px
+ import numpy as np
+ import pandas as pd

Maps


> df = px.data.carshare()
+ fig = px.scatter_mapbox(df, lat="centroid_lat", 
+ lon="centroid_lon", color="peak_hour", 
+ size="car_hours",
+ color_continuous_scale=px.colors.cyclical.IceFire,
+ size_max=15, zoom=10,
+ mapbox_style="carto-positron")
+ 
+ fig.write_html("map1.html")
> htmltools::includeHTML('map1.html')
> df = px.data.election()
+ geojson = px.data.election_geojson()
+ 
+ fig = px.choropleth_mapbox(df, geojson=geojson, color="Bergeron",locations="district", featureidkey="properties.district",
+ center={"lat": 45.5517, "lon": -73.7073},
+ mapbox_style="carto-positron", zoom=9)
+ 
+ fig.write_html("map2.html")
> htmltools::includeHTML('map2.html')
> df = px.data.gapminder()
+ fig = px.choropleth(df, locations="iso_alpha", 
+ color="lifeExp", hover_name="country", 
+ animation_frame="year", range_color=[20,80])
+ 
+ fig.write_html("map3.html")
> htmltools::includeHTML('map3.html')

Polar Coordinates

> df = px.data.wind()
+ fig = px.scatter_polar(df, r="frequency", theta="direction", 
+ color="strength", symbol="strength",
+ color_discrete_sequence=px.colors.sequential.Plasma_r)
+ 
+ fig.write_html("map4.html")
> htmltools::includeHTML('map4.html')
> fig = px.bar_polar(df, r="frequency", theta="direction", 
+ color="strength", template="plotly_dark",
+ color_discrete_sequence= px.colors.sequential.Plasma_r)
+ 
+ fig.write_html("map5.html")
> htmltools::includeHTML('map5.html')

Choropleth US Maps

The setup is different when not using plotly.express.

Setup

> import plotly
+ import plotly.offline as py
+ import plotly.graph_objs as go

You start with a data dictionary. The easiest way to do this is to use the dict() function of the general form:

  • type = ‘choropleth’,
  • locations = list of states
  • locationmode = ‘USA-states’
  • colorscale=

Either a predefined string:

‘pairs’ | ‘Greys’ | ‘Greens’ | ‘Bluered’ | ‘Hot’ | ‘Picnic’ | ‘Portland’ | ‘Jet’ | ‘RdBu’ | ‘Blackbody’ | ‘Earth’ | ‘Electric’ | ‘YIOrRd’ | ‘YIGnBu’

or create a custom colorscale

  • text= list or array of text to display per point
  • z= array of values on z axis (color of state)
  • colorbar = {‘title’:‘Colorbar Title’})

Here is a simple example:

> data = dict(type = 'choropleth',
+             locations = ['AZ','CA','NY'],
+             locationmode = 'USA-states',
+             colorscale= 'Portland',
+             text= ['text1','text2','text3'],
+             z=[1.0,2.0,3.0],
+             colorbar = {'title':'Colorbar Title'})
> layout = dict(geo = {'scope':'usa'})
> fig = dict(data=data, layout=layout)
> py.plot(fig, filename='map6.html', auto_open=False)
'map6.html'
> htmltools::includeHTML('map6.html')

Real Data US Map Choropleth

> df = pd.read_csv('2011_US_AGRI_Exports')
> df.head()
  code        state  ...   cotton                                               text
0   AL      Alabama  ...   317.61  Alabama<br>Beef 34.4 Dairy 4.06<br>Fruits 25.1...
1   AK       Alaska  ...     0.00  Alaska<br>Beef 0.2 Dairy 0.19<br>Fruits 0.0 Ve...
2   AZ      Arizona  ...   423.95  Arizona<br>Beef 71.3 Dairy 105.48<br>Fruits 60...
3   AR     Arkansas  ...   665.44  Arkansas<br>Beef 53.2 Dairy 3.53<br>Fruits 6.8...
4   CA   California  ...  1064.95   California<br>Beef 228.7 Dairy 929.95<br>Frui...

[5 rows x 18 columns]
> data = dict(type='choropleth',
+             colorscale = 'peach',
+             locations = df['code'],
+             z = df['total exports'],
+             locationmode = 'USA-states',
+             text = df['text'],
+             marker = dict(line = dict(color = 'rgb(255,255,255)',width = 2)),
+             colorbar = {'title':"Millions USD"}
+             ) 
> layout = dict(title = '2011 US Agriculture Exports by State',
+               geo = dict(scope='usa',
+                          showlakes = True,
+                          lakecolor = 'rgb(85,173,240)')
+              )
> fig = dict(data=data, layout=layout)
> py.plot(fig, filename='map7.html', auto_open=False)
'map7.html'
> htmltools::includeHTML('map7.html')

World Choropleth Map

> df = pd.read_csv('2014_World_GDP')
> df.head()
          COUNTRY  GDP (BILLIONS) CODE
0     Afghanistan           21.71  AFG
1         Albania           13.40  ALB
2         Algeria          227.80  DZA
3  American Samoa            0.75  ASM
4         Andorra            4.80  AND
> data = dict(
+         type = 'choropleth',
+         locations = df['CODE'],
+         z = df['GDP (BILLIONS)'],
+         text = df['COUNTRY'],
+         colorbar = {'title' : 'GDP Billions US'},
+       )
> layout = dict(
+     title = '2014 Global GDP',
+     geo = dict(
+         showframe = False,
+         projection = {'type':'mercator'}
+     )
+ )
> fig = dict(data=data, layout=layout)
> py.plot(fig, filename='map8.html', auto_open=False)
'map8.html'
> htmltools::includeHTML('map8.html')