Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!
Note: United States County Choropleths
are available in version 2.5.1+
Run pip install plotly --upgrade
to update your Plotly version
import plotly
plotly.__version__
'3.6.1'
geopandas
, pyshp
and shapely
must be installed for this figure factory.
Run the following commands to install the correct versions of the following modules:
pip install geopandas==0.3.0
pip install pyshp==1.2.10
pip install shapely==1.6.3
If you are using Windows, follow this post to properly install geopandas and dependencies: http://geoffboeing.com/2014/09/using-geopandas-windows/. If you are using Anaconda, do not use PIP to install the packages above. Instead use conda to install them:
conda install plotly
conda install geopandas
Every US state and county has an assined ID regulated by the US Federal Government under the term FIPS (Federal Information Processing Standards) codes. There are state codes and county codes: the 2016 state and county FIPS codes can be found at the US Census Website.
Combine a state FIPS code (eg. 06
for California) with a county FIPS code of the state (eg. 059
for Orange county) and this new state-county FIPS code (06059
) uniquely refers to the specified state and county.
ff.create_choropleth
only needs a list of FIPS codes and a list of values. Each FIPS code points to one county and each corresponding value in values
determines the color of the county.
A simple example of this is a choropleth a few counties in California:
import plotly.plotly as py
import plotly.figure_factory as ff
fips = ['06021', '06023', '06027',
'06029', '06033', '06059',
'06047', '06049', '06051',
'06055', '06061']
values = range(len(fips))
fig = ff.create_choropleth(fips=fips, values=values)
py.iplot(fig, filename='choropleth of some cali counties - full usa scope')
Even if your FIPS values belong to a single state, the scope defaults to the entire United States as displayed in the example above. Changing the scope of the choropleth shifts the zoom and position of the USA map. You can define the scope with a list of state names and the zoom will automatically adjust to include the state outlines of the selected states.
By default scope
is set to ['USA']
which the API treats as identical to passing a list of all 50 state names:
['AK', 'AL', 'CA', ...]
State abbreviations (eg. CA
) or the proper names (eg. California
) as strings are accepted. If the state name is not recognized, the API will throw a Warning and indicate which FIPS values were ignored.
Another param used in the example below is binning_endpoints
. If your values
is a list of numbers, you can bin your values into half-open intervals on the real line.
import plotly.plotly as py
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv')
df_sample_r = df_sample[df_sample['STNAME'] == 'California']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
colorscale = [
'rgb(193, 193, 193)',
'rgb(239,239,239)',
'rgb(195, 196, 222)',
'rgb(144,148,194)',
'rgb(101,104,168)',
'rgb(65, 53, 132)'
]
fig = ff.create_choropleth(
fips=fips, values=values, scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'],
binning_endpoints=[14348, 63983, 134827, 426762, 2081313], colorscale=colorscale,
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, round_legend_values=True,
legend_title='Population by County', title='California and Nearby States'
)
py.iplot(fig, filename='choropleth_california_and_surr_states_outlines')
import plotly.plotly as py
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv')
df_sample_r = df_sample[df_sample['STNAME'] == 'Florida']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
endpts = list(np.mgrid[min(values):max(values):4j])
colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0",
"#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"]
fig = ff.create_choropleth(
fips=fips, values=values, scope=['Florida'], show_state_data=True,
colorscale=colorscale, binning_endpoints=endpts, round_legend_values=True,
plot_bgcolor='rgb(229,229,229)',
paper_bgcolor='rgb(229,229,229)',
legend_title='Population by County',
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
exponent_format=True,
)
py.iplot(fig, filename='choropleth_florida')
import plotly.plotly as py
import plotly.figure_factory as ff
import pandas as pd
NE_states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island', 'Vermont']
df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv')
df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)]
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
colorscale = [
'rgb(68.0, 1.0, 84.0)',
'rgb(66.0, 64.0, 134.0)',
'rgb(38.0, 130.0, 142.0)',
'rgb(63.0, 188.0, 115.0)',
'rgb(216.0, 226.0, 25.0)'
]
fig = ff.create_choropleth(
fips=fips, values=values,
scope=NE_states, county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
legend_title='Population per county'
)
fig['layout']['legend'].update({'x': 0})
fig['layout']['annotations'][0].update({'x': -0.12, 'xanchor': 'left'})
py.iplot(fig, filename='choropleth_new_england')
Below is a choropleth that uses several other parameters. For a full list of all available params call help(ff.create_choropleth)
simplify_county
determines the simplification factor for the counties. The larger the number, the fewer vertices and edges each polygon has. See http://toblerity.org/shapely/manual.html#object.simplify for more information.simplify_state
simplifies the state outline polygon. See the documentation for more information.Default for both simplify_county
and simplif_state
is 0.02
Note: This choropleth uses a divergent categorical colorscale. See http://react-colorscales.getforge.io/ for other cool colorscales.
import plotly.figure_factory as ff
import pandas as pd
scope = ['Oregon']
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'
)
df_sample_r = df_sample[df_sample['STNAME'].isin(scope)]
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
colorscale = ["#8dd3c7", "#ffffb3", "#bebada", "#fb8072",
"#80b1d3", "#fdb462", "#b3de69", "#fccde5",
"#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f",
"#8dd3c7", "#ffffb3", "#bebada", "#fb8072",
"#80b1d3", "#fdb462", "#b3de69", "#fccde5",
"#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f",
"#8dd3c7", "#ffffb3", "#bebada", "#fb8072",
"#80b1d3", "#fdb462", "#b3de69", "#fccde5",
"#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f"]
fig = ff.create_choropleth(
fips=fips, values=values, scope=scope,
colorscale=colorscale, round_legend_values=True,
simplify_county=0, simplify_state=0,
county_outline={'color': 'rgb(15, 15, 55)', 'width': 0.5},
state_outline={'width': 1},
legend_title='pop. per county',
title='Oregon'
)
py.iplot(fig, filename='choropleth_oregon_ono_simplification_factor')
import plotly.plotly as py
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv')
df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(lambda x: str(x).zfill(2))
df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(lambda x: str(x).zfill(3))
df_sample['FIPS'] = df_sample['State FIPS Code'] + df_sample['County FIPS Code']
colorscale = ["#f7fbff","#ebf3fb","#deebf7","#d2e3f3","#c6dbef","#b3d2e9","#9ecae1",
"#85bcdb","#6baed6","#57a0ce","#4292c6","#3082be","#2171b5","#1361a9",
"#08519c","#0b4083","#08306b"]
endpts = list(np.linspace(1, 12, len(colorscale) - 1))
fips = df_sample['FIPS'].tolist()
values = df_sample['Unemployment Rate (%)'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values,
binning_endpoints=endpts,
colorscale=colorscale,
show_state_data=False,
show_hover=True, centroid_marker={'opacity': 0},
asp=2.9, title='USA by Unemployment %',
legend_title='% unemployed'
)
py.iplot(fig, filename='choropleth_full_usa')
The draw time for this plot will be slow for clients without much RAM.
/home/michael/.virtualenvs/plot2py2/local/lib/python2.7/site-packages/plotly/api/v1/clientresp.py:40: UserWarning: Estimated Draw Time Slow
Also see Mapbox county choropleths made in Python: https://plotly.com/python/mapbox-county-choropleth/
help(ff.create_choropleth)
Help on function create_choropleth in module plotly.figure_factory._county_choropleth: create_choropleth(fips, values, scope=['usa'], binning_endpoints=None, colorscale=None, order=None, simplify_county=0.02, simplify_state=0.02, asp=None, show_hover=True, show_state_data=True, state_outline=None, county_outline=None, centroid_marker=None, round_legend_values=False, exponent_format=False, legend_title='', **layout_options) Returns figure for county choropleth. Uses data from package_data. :param (list) fips: list of FIPS values which correspond to the con catination of state and county ids. An example is '01001'. :param (list) values: list of numbers/strings which correspond to the fips list. These are the values that will determine how the counties are colored. :param (list) scope: list of states and/or states abbreviations. Fits all states in the camera tightly. Selecting ['usa'] is the equivalent of appending all 50 states into your scope list. Selecting only 'usa' does not include 'Alaska', 'Puerto Rico', 'American Samoa', 'Commonwealth of the Northern Mariana Islands', 'Guam', 'United States Virgin Islands'. These must be added manually to the list. Default = ['usa'] :param (list) binning_endpoints: ascending numbers which implicitly define real number intervals which are used as bins. The colorscale used must have the same number of colors as the number of bins and this will result in a categorical colormap. :param (list) colorscale: a list of colors with length equal to the number of categories of colors. The length must match either all unique numbers in the 'values' list or if endpoints is being used, the number of categories created by the endpoints. For example, if binning_endpoints = [4, 6, 8], then there are 4 bins: [-inf, 4), [4, 6), [6, 8), [8, inf) :param (list) order: a list of the unique categories (numbers/bins) in any desired order. This is helpful if you want to order string values to a chosen colorscale. :param (float) simplify_county: determines the simplification factor for the counties. The larger the number, the fewer vertices and edges each polygon has. See http://toblerity.org/shapely/manual.html#object.simplify for more information. Default = 0.02 :param (float) simplify_state: simplifies the state outline polygon. See http://toblerity.org/shapely/manual.html#object.simplify for more information. Default = 0.02 :param (float) asp: the width-to-height aspect ratio for the camera. Default = 2.5 :param (bool) show_hover: show county hover and centroid info :param (bool) show_state_data: reveals state boundary lines :param (dict) state_outline: dict of attributes of the state outline including width and color. See https://plotly.com/python/reference/#scatter-marker-line for all valid params :param (dict) county_outline: dict of attributes of the county outline including width and color. See https://plotly.com/python/reference/#scatter-marker-line for all valid params :param (dict) centroid_marker: dict of attributes of the centroid marker. The centroid markers are invisible by default and appear visible on selection. See https://plotly.com/python/reference/#scatter-marker for all valid params :param (bool) round_legend_values: automatically round the numbers that appear in the legend to the nearest integer. Default = False :param (bool) exponent_format: if set to True, puts numbers in the K, M, B number format. For example 4000.0 becomes 4.0K Default = False :param (str) legend_title: title that appears above the legend :param **layout_options: a **kwargs argument for all layout parameters Example 1: Florida ``` import plotly.plotly as py import plotly.figure_factory as ff import numpy as np import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'] == 'Florida'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() binning_endpoints = list(np.mgrid[min(values):max(values):4j]) colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0", "#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"] fig = ff.create_choropleth( fips=fips, values=values, scope=['Florida'], show_state_data=True, colorscale=colorscale, binning_endpoints=binning_endpoints, round_legend_values=True, plot_bgcolor='rgb(229,229,229)', paper_bgcolor='rgb(229,229,229)', legend_title='Florida Population', county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, exponent_format=True, ) py.iplot(fig, filename='choropleth_florida') ``` Example 2: New England ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd NE_states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island'] df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)] colorscale = ['rgb(68.0, 1.0, 84.0)', 'rgb(66.0, 64.0, 134.0)', 'rgb(38.0, 130.0, 142.0)', 'rgb(63.0, 188.0, 115.0)', 'rgb(216.0, 226.0, 25.0)'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() fig = ff.create_choropleth( fips=fips, values=values, scope=NE_states, show_state_data=True ) py.iplot(fig, filename='choropleth_new_england') ``` Example 3: California and Surrounding States ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'] == 'California'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() colorscale = [ 'rgb(193, 193, 193)', 'rgb(239,239,239)', 'rgb(195, 196, 222)', 'rgb(144,148,194)', 'rgb(101,104,168)', 'rgb(65, 53, 132)' ] fig = ff.create_choropleth( fips=fips, values=values, colorscale=colorscale, scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'], binning_endpoints=[14348, 63983, 134827, 426762, 2081313], county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, legend_title='California Counties', title='California and Nearby States' ) py.iplot(fig, filename='choropleth_california_and_surr_states_outlines') ``` Example 4: USA ``` import plotly.plotly as py import plotly.figure_factory as ff import numpy as np import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv' ) df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply( lambda x: str(x).zfill(2) ) df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply( lambda x: str(x).zfill(3) ) df_sample['FIPS'] = ( df_sample['State FIPS Code'] + df_sample['County FIPS Code'] ) binning_endpoints = list(np.linspace(1, 12, len(colorscale) - 1)) colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef", "#b3d2e9", "#9ecae1", "#85bcdb", "#6baed6", "#57a0ce", "#4292c6", "#3082be", "#2171b5", "#1361a9", "#08519c", "#0b4083","#08306b"] fips = df_sample['FIPS'] values = df_sample['Unemployment Rate (%)'] fig = ff.create_choropleth( fips=fips, values=values, scope=['usa'], binning_endpoints=binning_endpoints, colorscale=colorscale, show_hover=True, centroid_marker={'opacity': 0}, asp=2.9, title='USA by Unemployment %', legend_title='Unemployment %' ) py.iplot(fig, filename='choropleth_full_usa') ```
from IPython.display import display, HTML
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))
! pip install git+https://github.com/plotly/publisher.git --upgrade
import publisher
publisher.publish(
'county_choropleth.ipynb', 'python/county-choropleth/', 'USA County Choropleth Maps',
'How to create colormaped representations of USA counties by FIPS values in Python.',
title = 'Python USA County Choropleth Maps | Plotly',
has_thumbnail='true', thumbnail='thumbnail/county-choropleth-usa-greybkgd.jpg',
language='python', page_type='example_index',
display_as='maps', order=0,
uses_plotly_offline=False,ipynb='~notebook_demo/212')
Collecting git+https://github.com/plotly/publisher.git
Cloning https://github.com/plotly/publisher.git to /tmp/pip-req-build-h71Kdm
Building wheels for collected packages: publisher
Running setup.py bdist_wheel for publisher ... done
Stored in directory: /tmp/pip-ephem-wheel-cache-37a0oz/wheels/99/3e/a0/fbd22ba24cca72bdbaba53dbc23c1768755fb17b3af0f33966
Successfully built publisher
Installing collected packages: publisher
Successfully installed publisher-0.11
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
/home/michael/.virtualenvs/plot2py2/local/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning: The `IPython.nbconvert` package has been deprecated since IPython 4.0. You should import from nbconvert instead. /home/michael/.virtualenvs/plot2py2/local/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning: Did you "Save" this notebook before running this command? Remember to save, always save.