diff --git a/_posts/python/maps/choropleth-maps/2015-06-30-Choropleth_maps.html b/_posts/python/maps/choropleth-maps/2015-06-30-Choropleth_maps.html index 45988c8e0dba..9de934652627 100644 --- a/_posts/python/maps/choropleth-maps/2015-06-30-Choropleth_maps.html +++ b/_posts/python/maps/choropleth-maps/2015-06-30-Choropleth_maps.html @@ -1,38 +1,35 @@ --- permalink: python/choropleth-maps/ -description: How to make Choropleth maps in Python with Plotly. -name: Choropleth Maps | plotly +description: How to make choropleth maps in Python with Plotly. +name: Choropleth Maps has_thumbnail: true thumbnail: thumbnail/choropleth.jpg layout: user-guide -name: Choropleth Maps language: python -title: Choropleth Maps | plotly +title: Python Choropleth Maps | Plotly display_as: maps has_thumbnail: true -page_type: example_index -order: 1 ipynb: ~notebook_demo/55 +order: 1 +page_type: u-guide --- {% raw %} -
-
+
-

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer. +

New to Plotly?¶

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!

-
-
+
-

United States Choropleth Map

+

United States Choropleth Map¶

@@ -95,10 +92,14 @@

United States Choropleth Map -
Out[1]:
+
+ +
Out[1]:
+ +
- +
@@ -107,12 +108,11 @@

United States Choropleth Map -
+
-

World Choropleth Map

+

World Choropleth Map¶

@@ -171,10 +171,14 @@

World Choropleth Map -
Out[2]:
+
+ +
Out[2]:
+ +
- +
@@ -183,12 +187,11 @@

World Choropleth Map -
+
-

Choropleth Inset Map

+

Choropleth Inset Map¶

@@ -299,10 +302,14 @@

Choropleth Inset Map -
Out[3]:
+
+ +
Out[3]:
+ +
- +
@@ -311,12 +318,12 @@

Choropleth Inset Map -
+
-

PACE Approved Legislation

+

Full County Choropleths¶

For the full county choropleth doc page checkout https://plot.ly/python/county-choropleth/

+
@@ -326,103 +333,32 @@

PACE Approved Legislation
import plotly.plotly as py
-from plotly.graph_objs import *
-
-trace1 = Choropleth(
-    z=['1', '1', '1', '1', '1', '1', '1'],
-    autocolorscale=False,
-    colorscale=[[0, 'rgb(255,255,255)'], [1, 'rgb(186,58,51)']],
-    hoverinfo='text',
-    locationmode='USA-states',
-    locations=['AR', 'GA', 'KY', 'MO', 'UT', 'TX', 'WY'],
-    name='Republican',
-    showscale=False,
-    text=['Arkansas', 'Georgia', 'Kentucky', 'Missouri', 'Utah', 'Texas', 'Wyoming'],
-    zauto=False,
-    zmax=1,
-    zmin=0,
-)
-trace2 = Choropleth(
-    z=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
-    autocolorscale=False,
-    colorscale=[[0, 'rgb(255,255,255)'], [1, 'rgb(68,94,150)']],
-    hoverinfo='text',
-    locationmode='USA-states',
-    locations=['CA', 'CI', 'DOC', 'IL', 'MD', 'NJ', 'NM', 'NY', 'OR', 'RI', 'VT'],
-    name='Democrat',
-    showscale=False,
-    text=['California', 'Connecticut', 'District of Columbia', 'Illinois', 
-          'Maryland', 'New Jersey', 'New Mexico', 'New York', 'Oregon',
-          'Rhode Island', 'Vermont'],
-    zauto=False,
-    zmax=1,
-    zmin=0,
-)
-trace3 = Choropleth(
-    z=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
-    autocolorscale=False,
-    colorscale=[[0, 'rgb(255, 255, 255)'], [1, 'rgb(187, 170, 144)']],
-    hoverinfo='text',
-    locationmode='USA-states',
-    locations=['CO', 'FL', 'MI', 'MN', 'NH', 'OH', 'VA', 'WI'],
-    name='Swing State',
-    showscale=False,
-    text=['Colorado', 'Florida', 'Michigan', 'Minnesota', 
-          'New Hampshire', 'Ohio', 'Virginia', 'Wisconsin'],
-    zauto=False,
-    zmax=1,
-    zmin=0,
-)
+import plotly.figure_factory as ff
 
-data = Data([trace1, trace2, trace3])
-layout = Layout(
-    autosize=False,
-    geo=dict(
-        countrycolor='rgb(102, 102, 102)',
-        countrywidth=0.1,
-        lakecolor='rgb(255, 255, 255)',
-        landcolor='rgba(237, 247, 138, 0.28)',
-        lonaxis=dict(
-            gridwidth=1.5999999999999999,
-            range=[-180, -50],
-            showgrid=False
-        ),
-        projection=dict(
-            type='albers usa'
-        ),
-        scope='usa',
-        showland=True,
-        showrivers=False,
-        showsubunits=True,
-        subunitcolor='rgb(102, 102, 102)',
-        subunitwidth=0.5
-    ),
-    hovermode='closest',
-    images=list([
-        dict(
-            x=1,
-            y=0.6,
-            sizex=0.155,
-            sizey=0.4,
-            source='http://i.imgur.com/Xe3f1zg.png',
-            xanchor='right',
-            xref='paper',
-            yanchor='bottom',
-            yref='paper'
-        )
-    ]),
-    showlegend=True,
-    title='<b>PACE Approved legislation</b>',
-    width= 800,
-    margin = dict(
-        l=0,
-        r=50,
-        b=100,
-        t=100,
-        pad=4)
+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, scope=['usa'],
+    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'
 )
-fig = Figure(data=data, layout=layout)
-py.iplot(fig, filename='pace')
+py.iplot(fig, filename='choropleth_full_usa')
 
@@ -433,10 +369,39 @@

PACE Approved Legislation -
Out[4]:
+
+ +
+ + +
+
The draw time for this plot will be slow for clients without much RAM.
+
+
+
+ +
+ +
+ + +
+
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/plotly/api/v1/clientresp.py:40: UserWarning:
+
+Estimated Draw Time Slow
+
+
+
+
+ +
+ +
Out[4]:
+ +
- +
@@ -445,13 +410,15 @@

PACE Approved Legislation -
+
-

Reference

See https://plot.ly/python/reference/#choropleth for more information and chart attribute options!

+

Reference¶

See https://plot.ly/python/reference/#choropleth for more information and chart attribute options!

-
{% endraw %} \ No newline at end of file +
+ + +{% endraw %} \ No newline at end of file diff --git a/_posts/python/maps/choropleth-maps/Choropleth_maps.ipynb b/_posts/python/maps/choropleth-maps/Choropleth_maps.ipynb old mode 100755 new mode 100644 index ec745d1cb759..515aaf0af226 --- a/_posts/python/maps/choropleth-maps/Choropleth_maps.ipynb +++ b/_posts/python/maps/choropleth-maps/Choropleth_maps.ipynb @@ -14,20 +14,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### United States Choropleth Map" + "#### United States Choropleth Map" ] }, { "cell_type": "code", "execution_count": 1, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" @@ -89,20 +87,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### World Choropleth Map" + "#### World Choropleth Map" ] }, { "cell_type": "code", "execution_count": 2, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" @@ -160,20 +156,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Choropleth Inset Map" + "#### Choropleth Inset Map" ] }, { "cell_type": "code", "execution_count": 3, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" @@ -276,136 +270,81 @@ ")\n", "\n", "fig = go.Figure(layout=layout, data=cases+inset)\n", - "py.iplot(fig, validate=False, filename='West Africa Ebola cases 2014')\n" + "py.iplot(fig, validate=False, filename='West Africa Ebola cases 2014')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### PACE Approved Legislation " + "#### Full County Choropleths\n", + "For the full county choropleth doc page checkout https://plot.ly/python/county-choropleth/" ] }, { "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, + "execution_count": 4, + "metadata": {}, "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The draw time for this plot will be slow for clients without much RAM.\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/plotly/api/v1/clientresp.py:40: UserWarning:\n", + "\n", + "Estimated Draw Time Slow\n", + "\n" + ] + }, { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" ] }, - "execution_count": 1, + "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", - "from plotly.graph_objs import *\n", + "import plotly.figure_factory as ff\n", "\n", - "trace1 = Choropleth(\n", - " z=['1', '1', '1', '1', '1', '1', '1'],\n", - " autocolorscale=False,\n", - " colorscale=[[0, 'rgb(255,255,255)'], [1, 'rgb(186,58,51)']],\n", - " hoverinfo='text',\n", - " locationmode='USA-states',\n", - " locations=['AR', 'GA', 'KY', 'MO', 'UT', 'TX', 'WY'],\n", - " name='Republican',\n", - " showscale=False,\n", - " text=['Arkansas', 'Georgia', 'Kentucky', 'Missouri', 'Utah', 'Texas', 'Wyoming'],\n", - " zauto=False,\n", - " zmax=1,\n", - " zmin=0,\n", - ")\n", - "trace2 = Choropleth(\n", - " z=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],\n", - " autocolorscale=False,\n", - " colorscale=[[0, 'rgb(255,255,255)'], [1, 'rgb(68,94,150)']],\n", - " hoverinfo='text',\n", - " locationmode='USA-states',\n", - " locations=['CA', 'CI', 'DOC', 'IL', 'MD', 'NJ', 'NM', 'NY', 'OR', 'RI', 'VT'],\n", - " name='Democrat',\n", - " showscale=False,\n", - " text=['California', 'Connecticut', 'District of Columbia', 'Illinois', \n", - " 'Maryland', 'New Jersey', 'New Mexico', 'New York', 'Oregon',\n", - " 'Rhode Island', 'Vermont'],\n", - " zauto=False,\n", - " zmax=1,\n", - " zmin=0,\n", - ")\n", - "trace3 = Choropleth(\n", - " z=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],\n", - " autocolorscale=False,\n", - " colorscale=[[0, 'rgb(255, 255, 255)'], [1, 'rgb(187, 170, 144)']],\n", - " hoverinfo='text',\n", - " locationmode='USA-states',\n", - " locations=['CO', 'FL', 'MI', 'MN', 'NH', 'OH', 'VA', 'WI'],\n", - " name='Swing State',\n", - " showscale=False,\n", - " text=['Colorado', 'Florida', 'Michigan', 'Minnesota', \n", - " 'New Hampshire', 'Ohio', 'Virginia', 'Wisconsin'],\n", - " zauto=False,\n", - " zmax=1,\n", - " zmin=0,\n", - ")\n", + "import numpy as np\n", + "import pandas as pd\n", "\n", - "data = Data([trace1, trace2, trace3])\n", - "layout = Layout(\n", - " autosize=False,\n", - " geo=dict(\n", - " countrycolor='rgb(102, 102, 102)',\n", - " countrywidth=0.1,\n", - " lakecolor='rgb(255, 255, 255)',\n", - " landcolor='rgba(237, 247, 138, 0.28)',\n", - " lonaxis=dict(\n", - " gridwidth=1.5999999999999999,\n", - " range=[-180, -50],\n", - " showgrid=False\n", - " ),\n", - " projection=dict(\n", - " type='albers usa'\n", - " ),\n", - " scope='usa',\n", - " showland=True,\n", - " showrivers=False,\n", - " showsubunits=True,\n", - " subunitcolor='rgb(102, 102, 102)',\n", - " subunitwidth=0.5\n", - " ),\n", - " hovermode='closest',\n", - " images=list([\n", - " dict(\n", - " x=1,\n", - " y=0.6,\n", - " sizex=0.155,\n", - " sizey=0.4,\n", - " source='http://i.imgur.com/Xe3f1zg.png',\n", - " xanchor='right',\n", - " xref='paper',\n", - " yanchor='bottom',\n", - " yref='paper'\n", - " )\n", - " ]),\n", - " showlegend=True,\n", - " title='PACE Approved legislation',\n", - " width= 800,\n", - " margin = dict(\n", - " l=0,\n", - " r=50,\n", - " b=100,\n", - " t=100,\n", - " pad=4)\n", + "df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv')\n", + "df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(lambda x: str(x).zfill(2))\n", + "df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(lambda x: str(x).zfill(3))\n", + "df_sample['FIPS'] = df_sample['State FIPS Code'] + df_sample['County FIPS Code']\n", + "\n", + "colorscale = [\"#f7fbff\",\"#ebf3fb\",\"#deebf7\",\"#d2e3f3\",\"#c6dbef\",\"#b3d2e9\",\"#9ecae1\",\n", + " \"#85bcdb\",\"#6baed6\",\"#57a0ce\",\"#4292c6\",\"#3082be\",\"#2171b5\",\"#1361a9\",\n", + " \"#08519c\",\"#0b4083\",\"#08306b\"]\n", + "endpts = list(np.linspace(1, 12, len(colorscale) - 1))\n", + "fips = df_sample['FIPS'].tolist()\n", + "values = df_sample['Unemployment Rate (%)'].tolist()\n", + "\n", + "fig = ff.create_choropleth(\n", + " fips=fips, values=values, scope=['usa'],\n", + " binning_endpoints=endpts, colorscale=colorscale,\n", + " show_state_data=False,\n", + " show_hover=True, centroid_marker={'opacity': 0},\n", + " asp=2.9, title='USA by Unemployment %',\n", + " legend_title='% unemployed'\n", ")\n", - "fig = Figure(data=data, layout=layout)\n", - "py.iplot(fig, filename='pace')" + "py.iplot(fig, filename='choropleth_full_usa')" ] }, { @@ -418,14 +357,8 @@ }, { "cell_type": "code", -<<<<<<< HEAD "execution_count": 1, -======= - "execution_count": 2, ->>>>>>> b22a31ab6cd91d151ab51741f3fcb448574008a5 - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "data": { @@ -456,58 +389,22 @@ "output_type": "stream", "text": [ "Collecting git+https://github.com/plotly/publisher.git\n", -<<<<<<< HEAD - " Cloning https://github.com/plotly/publisher.git to /var/folders/ld/6cl3s_l50wd40tdjq2b03jxh0000gp/T/pip-k8JnpP-build\n", + " Cloning https://github.com/plotly/publisher.git to /private/var/folders/tc/bs9g6vrd36q74m5t8h9cgphh0000gn/T/pip-OKLJ7r-build\n", "Installing collected packages: publisher\n", " Found existing installation: publisher 0.11\n", " Uninstalling publisher-0.11:\n", " Successfully uninstalled publisher-0.11\n", - " Running setup.py install for publisher ... \u001b[?25l-\b \b\\\b \bdone\n", - "\u001b[?25hSuccessfully installed publisher-0.10\n" -======= - " Cloning https://github.com/plotly/publisher.git to /tmp/pip-ittp0v-build\n", - "Installing collected packages: publisher\n", - " Running setup.py install for publisher ... \u001b[?25l-\b \berror\n", - " Complete output from command /usr/bin/python -u -c \"import setuptools, tokenize;__file__='/tmp/pip-ittp0v-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec'))\" install --record /tmp/pip-lGFm1Y-record/install-record.txt --single-version-externally-managed --compile:\n", - " running install\n", - " running build\n", - " running build_py\n", - " creating build\n", - " creating build/lib.linux-x86_64-2.7\n", - " creating build/lib.linux-x86_64-2.7/publisher\n", - " copying publisher/publisher.py -> build/lib.linux-x86_64-2.7/publisher\n", - " copying publisher/__init__.py -> build/lib.linux-x86_64-2.7/publisher\n", - " running install_lib\n", - " creating /usr/local/lib/python2.7/dist-packages/publisher\n", - " error: could not create '/usr/local/lib/python2.7/dist-packages/publisher': Permission denied\n", - " \n", - " ----------------------------------------\n", - "\u001b[31mCommand \"/usr/bin/python -u -c \"import setuptools, tokenize;__file__='/tmp/pip-ittp0v-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec'))\" install --record /tmp/pip-lGFm1Y-record/install-record.txt --single-version-externally-managed --compile\" failed with error code 1 in /tmp/pip-ittp0v-build/\u001b[0m\n", - "\u001b[?25h" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/home/diksha/anaconda2/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning:\n", - "\n", - "The `IPython.nbconvert` package has been deprecated. You should import from nbconvert instead.\n", - "\n", - "/home/diksha/anaconda2/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning:\n", - "\n", - "Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", - "\n" ->>>>>>> b22a31ab6cd91d151ab51741f3fcb448574008a5 + " Running setup.py install for publisher ... \u001b[?25ldone\n", + "\u001b[?25hSuccessfully installed publisher-0.11\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ - "/Users/brandendunbar/Desktop/test/venv/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning: The `IPython.nbconvert` package has been deprecated. You should import from nbconvert instead.\n", + "/Library/Frameworks/Python.framework/Versions/2.7/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.\n", " \"You should import from nbconvert instead.\", ShimWarning)\n", - "/Users/brandendunbar/Desktop/test/venv/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning: Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", + "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning: Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", " warnings.warn('Did you \"Save\" this notebook before running this command? '\n" ] } @@ -521,14 +418,13 @@ "! pip install git+https://github.com/plotly/publisher.git --upgrade\n", "import publisher\n", "publisher.publish(\n", - " 'Choropleth_maps.ipynb', 'python/choropleth-maps/', 'Choropleth Maps | plotly',\n", - " 'How to make Choropleth maps in Python with Plotly.',\n", - " title = 'Choropleth Maps | plotly',\n", - " name = 'Choropleth Maps',\n", + " 'Choropleth_maps.ipynb', 'python/choropleth-maps/', 'Choropleth Maps',\n", + " 'How to make choropleth maps in Python with Plotly.',\n", + " title = 'Python Choropleth Maps | Plotly',\n", " has_thumbnail='true', thumbnail='thumbnail/choropleth.jpg', \n", - " language='python', page_type='example_index',\n", - " display_as='maps', order=1,\n", - " ipynb= '~notebook_demo/55')" + " language='python',\n", + " display_as='maps', order=1, ipynb='~notebook_demo/55',\n", + " uses_plotly_offline=False)" ] }, { @@ -542,7 +438,6 @@ } ], "metadata": { - "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 2", "language": "python", @@ -558,9 +453,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", - "version": "2.7.10" + "version": "2.7.12" } }, "nbformat": 4, - "nbformat_minor": 0 + "nbformat_minor": 1 } diff --git a/_posts/python/maps/county_choropleth/2015-06-30-county_choropleth.html b/_posts/python/maps/county_choropleth/2015-06-30-county_choropleth.html new file mode 100644 index 000000000000..4d0f037a20bd --- /dev/null +++ b/_posts/python/maps/county_choropleth/2015-06-30-county_choropleth.html @@ -0,0 +1,741 @@ +--- +permalink: python/county-choropleth/ +description: How to create colormaped representations of USA counties by FIPS values in Python. +name: USA County Choropleth Maps +has_thumbnail: true +thumbnail: thumbnail/county-choropleth-usa-greybkgd.jpg +layout: user-guide +language: python +title: Python USA County Choropleth Maps | Plotly +display_as: maps +has_thumbnail: true +page_type: example_index +order: 0 +--- +{% raw %} +
+
+
+
+

New to Plotly?¶

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!

+ +
+
+
+
+
+
+
+

Version Check¶

Note: United States County Choropleths are available in version 2.4.1+
+Run pip install plotly --upgrade to update your Plotly version

+ +
+
+
+
+
+
In [1]:
+
+
+
import plotly
+plotly.__version__
+
+ +
+
+
+ +
+
+ + +
+ +
Out[1]:
+ + + + +
+
'2.4.1'
+
+ +
+ +
+
+ +
+
+
+
+
+

FIPS and Values¶

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.

+ +
+
+
+
+
+
+
+

Simple Example¶

A simple example of this is a choropleth a few counties in California:

+ +
+
+
+
+
+
In [2]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[2]:
+ + + +
+ +
+ +
+ +
+
+ +
+
+
+
+
+

Change the 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.

+ +
+
+
+
+
+
In [3]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[3]:
+ + + +
+ +
+ +
+ +
+
+ +
+
+
+
+
+

Single State¶

+
+
+
+
+
+
In [4]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[4]:
+ + + +
+ +
+ +
+ +
+
+ +
+
+
+
+
+

Multiple States¶

+
+
+
+
+
+
In [5]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[5]:
+ + + +
+ +
+ +
+ +
+
+ +
+
+
+
+
+

Simplify County, State Lines¶

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.

+ +
+
+
+
+
+
In [10]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[10]:
+ + + +
+ +
+ +
+ +
+
+ +
+
+
+
+
+

The Entire USA¶

+
+
+
+
+
+
In [2]:
+
+
+
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.
+
+
+
+ +
+ +
Out[2]:
+ + + +
+ +
+ +
+ +
+
+ +
+
+
+
+
+

Reference¶

Note: the param offline_mode will be renamed in a future version of Plotly. Enabling does activate the unselected and selected features of the centroid scatter points but since these features exist in Plotly Reference Library, offline_mode can be set to True and run in online mode.

+

See https://plot.ly/python/reference/#scatter-selected and https://plot.ly/python/reference/#scatter-unselected

+ +
+
+
+
+
+
In [3]:
+
+
+
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, offline_mode=False, 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) offline_mode: if set to True, the centroids of each county
+        are invisible until selected over with a dragbox. Warning: this can
+        only be used if you are plotting in offline mode with validate set to
+        False as the params that are being added to the fig dictionary are not
+        yet part of the plotly.py python library. Stay tuned for updates.
+        Default = False
+    :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://plot.ly/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://plot.ly/python/reference/#scatter-marker-line for all valid
+        params
+    :param (dict) centroid_marker: dict of attributes of the centroid marker.
+        See https://plot.ly/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')
+    ```
+
+
+
+
+ +
+
+ +
+ + +{% endraw %} \ No newline at end of file diff --git a/_posts/python/maps/county_choropleth/2018-02-21-county-level-choropleth.html b/_posts/python/maps/county_choropleth/2018-02-21-county-level-choropleth.html new file mode 100644 index 000000000000..2a1e1e48e69b --- /dev/null +++ b/_posts/python/maps/county_choropleth/2018-02-21-county-level-choropleth.html @@ -0,0 +1,5 @@ +--- +permalink: python/county-level-choropleth/ +redirect_to: python/county-choropleth/ +sitemap: false +--- \ No newline at end of file diff --git a/_posts/python/maps/county_choropleth/county_choropleth.ipynb b/_posts/python/maps/county_choropleth/county_choropleth.ipynb new file mode 100644 index 000000000000..426d450709a3 --- /dev/null +++ b/_posts/python/maps/county_choropleth/county_choropleth.ipynb @@ -0,0 +1,748 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### New to Plotly?\n", + "Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).\n", + "
You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/#start-plotting-online).\n", + "
We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Version Check\n", + "Note: `United States County Choropleths` are available in version 2.4.1+
\n", + "Run `pip install plotly --upgrade` to update your Plotly version" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'2.4.1'" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import plotly\n", + "plotly.__version__" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### FIPS and Values\n", + "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](https://www.census.gov/geographies/reference-files/2016/demo/popest/2016-fips.html).\n", + "\n", + "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.\n", + "\n", + "`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." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Simple Example\n", + "A simple example of this is a choropleth a few counties in California:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import plotly.plotly as py\n", + "import plotly.figure_factory as ff\n", + "\n", + "fips = ['06021', '06023', '06027',\n", + " '06029', '06033', '06059',\n", + " '06047', '06049', '06051',\n", + " '06055', '06061']\n", + "values = range(len(fips))\n", + "\n", + "fig = ff.create_choropleth(fips=fips, values=values)\n", + "py.iplot(fig, filename='choropleth of some cali counties - full usa scope')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Change the Scope\n", + "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.\n", + "\n", + "By default `scope` is set to `['USA']` which the API treats as identical to passing a list of all 50 state names:
\n", + "\n", + "`['AK', 'AL', 'CA', ...]`\n", + "\n", + "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.\n", + "\n", + "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." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import plotly.plotly as py\n", + "import plotly.figure_factory as ff\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv')\n", + "df_sample_r = df_sample[df_sample['STNAME'] == 'California']\n", + "\n", + "values = df_sample_r['TOT_POP'].tolist()\n", + "fips = df_sample_r['FIPS'].tolist()\n", + "\n", + "colorscale = [\n", + " 'rgb(193, 193, 193)',\n", + " 'rgb(239,239,239)',\n", + " 'rgb(195, 196, 222)',\n", + " 'rgb(144,148,194)',\n", + " 'rgb(101,104,168)',\n", + " 'rgb(65, 53, 132)'\n", + "]\n", + "\n", + "fig = ff.create_choropleth(\n", + " fips=fips, values=values, scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'],\n", + " binning_endpoints=[14348, 63983, 134827, 426762, 2081313], colorscale=colorscale,\n", + " county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, round_legend_values=True,\n", + " legend_title='Population by County', title='California and Nearby States'\n", + ")\n", + "py.iplot(fig, filename='choropleth_california_and_surr_states_outlines')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Single State" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import plotly.plotly as py\n", + "import plotly.figure_factory as ff\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv')\n", + "df_sample_r = df_sample[df_sample['STNAME'] == 'Florida']\n", + "\n", + "values = df_sample_r['TOT_POP'].tolist()\n", + "fips = df_sample_r['FIPS'].tolist()\n", + "\n", + "endpts = list(np.mgrid[min(values):max(values):4j])\n", + "colorscale = [\"#030512\",\"#1d1d3b\",\"#323268\",\"#3d4b94\",\"#3e6ab0\",\n", + " \"#4989bc\",\"#60a7c7\",\"#85c5d3\",\"#b7e0e4\",\"#eafcfd\"]\n", + "fig = ff.create_choropleth(\n", + " fips=fips, values=values, scope=['Florida'], show_state_data=True,\n", + " colorscale=colorscale, binning_endpoints=endpts, round_legend_values=True,\n", + " plot_bgcolor='rgb(229,229,229)',\n", + " paper_bgcolor='rgb(229,229,229)',\n", + " legend_title='Population by County',\n", + " county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n", + " exponent_format=True,\n", + ")\n", + "py.iplot(fig, filename='choropleth_florida')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Multiple States" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import plotly.plotly as py\n", + "import plotly.figure_factory as ff\n", + "\n", + "import pandas as pd\n", + "\n", + "NE_states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island', 'Vermont']\n", + "df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv')\n", + "df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)]\n", + "\n", + "values = df_sample_r['TOT_POP'].tolist()\n", + "fips = df_sample_r['FIPS'].tolist()\n", + "\n", + "colorscale = [\n", + " 'rgb(68.0, 1.0, 84.0)',\n", + " 'rgb(66.0, 64.0, 134.0)',\n", + " 'rgb(38.0, 130.0, 142.0)',\n", + " 'rgb(63.0, 188.0, 115.0)',\n", + " 'rgb(216.0, 226.0, 25.0)'\n", + "]\n", + "\n", + "fig = ff.create_choropleth(\n", + " fips=fips, values=values,\n", + " scope=NE_states, county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n", + " legend_title='Population per county'\n", + " \n", + ")\n", + "fig['layout']['legend'].update({'x': 0})\n", + "fig['layout']['annotations'][0].update({'x': -0.12, 'xanchor': 'left'})\n", + "py.iplot(fig, filename='choropleth_new_england')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Simplify County, State Lines\n", + "Below is a choropleth that uses several other parameters. For a full list of all available params call `help(ff.create_choropleth)`\n", + "\n", + "- `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.\n", + "- `simplify_state` simplifies the state outline polygon. See the [documentation](http://toblerity.org/shapely/manual.html#object.simplify) for more information.\n", + "Default for both `simplify_county` and `simplif_state` is 0.02\n", + "\n", + "Note: This choropleth uses a divergent categorical colorscale. See http://react-colorscales.getforge.io/ for other cool colorscales." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import plotly.figure_factory as ff\n", + "\n", + "import pandas as pd\n", + "\n", + "scope = ['Oregon']\n", + "df_sample = pd.read_csv(\n", + " 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'\n", + ")\n", + "df_sample_r = df_sample[df_sample['STNAME'].isin(scope)]\n", + "\n", + "values = df_sample_r['TOT_POP'].tolist()\n", + "fips = df_sample_r['FIPS'].tolist()\n", + "\n", + "colorscale = [\"#8dd3c7\", \"#ffffb3\", \"#bebada\", \"#fb8072\",\n", + " \"#80b1d3\", \"#fdb462\", \"#b3de69\", \"#fccde5\",\n", + " \"#d9d9d9\", \"#bc80bd\", \"#ccebc5\", \"#ffed6f\",\n", + " \"#8dd3c7\", \"#ffffb3\", \"#bebada\", \"#fb8072\",\n", + " \"#80b1d3\", \"#fdb462\", \"#b3de69\", \"#fccde5\",\n", + " \"#d9d9d9\", \"#bc80bd\", \"#ccebc5\", \"#ffed6f\",\n", + " \"#8dd3c7\", \"#ffffb3\", \"#bebada\", \"#fb8072\",\n", + " \"#80b1d3\", \"#fdb462\", \"#b3de69\", \"#fccde5\",\n", + " \"#d9d9d9\", \"#bc80bd\", \"#ccebc5\", \"#ffed6f\"]\n", + "\n", + "fig = ff.create_choropleth(\n", + " fips=fips, values=values, scope=scope,\n", + " colorscale=colorscale, round_legend_values=True,\n", + " simplify_county=0, simplify_state=0,\n", + " county_outline={'color': 'rgb(15, 15, 55)', 'width': 0.5},\n", + " state_outline={'width': 1},\n", + " legend_title='pop. per county',\n", + " title='Oregon'\n", + ")\n", + "\n", + "py.iplot(fig, filename='choropleth_oregon_ono_simplification_factor')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### The Entire USA" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The draw time for this plot will be slow for clients without much RAM.\n" + ] + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import plotly.plotly as py\n", + "import plotly.figure_factory as ff\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv')\n", + "df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(lambda x: str(x).zfill(2))\n", + "df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(lambda x: str(x).zfill(3))\n", + "df_sample['FIPS'] = df_sample['State FIPS Code'] + df_sample['County FIPS Code']\n", + "\n", + "colorscale = [\"#f7fbff\",\"#ebf3fb\",\"#deebf7\",\"#d2e3f3\",\"#c6dbef\",\"#b3d2e9\",\"#9ecae1\",\n", + " \"#85bcdb\",\"#6baed6\",\"#57a0ce\",\"#4292c6\",\"#3082be\",\"#2171b5\",\"#1361a9\",\n", + " \"#08519c\",\"#0b4083\",\"#08306b\"]\n", + "endpts = list(np.linspace(1, 12, len(colorscale) - 1))\n", + "fips = df_sample['FIPS'].tolist()\n", + "values = df_sample['Unemployment Rate (%)'].tolist()\n", + "\n", + "fig = ff.create_choropleth(\n", + " fips=fips, values=values,\n", + " binning_endpoints=endpts,\n", + " colorscale=colorscale,\n", + " show_state_data=False,\n", + " show_hover=True, centroid_marker={'opacity': 0},\n", + " asp=2.9, title='USA by Unemployment %',\n", + " legend_title='% unemployed'\n", + ")\n", + "py.iplot(fig, filename='choropleth_full_usa')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Reference\n", + "Note: the param `offline_mode` will be renamed in a future version of Plotly. Enabling _does_ activate the `unselected` and `selected` features of the centroid scatter points but since these features exist in Plotly Reference Library, `offline_mode` can be set to `True` and run in online mode.\n", + "\n", + "See https://plot.ly/python/reference/#scatter-selected and https://plot.ly/python/reference/#scatter-unselected" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on function create_choropleth in module plotly.figure_factory._county_choropleth:\n", + "\n", + "create_choropleth(fips, values, scope=['usa'], binning_endpoints=None, colorscale=None, order=None, simplify_county=0.02, simplify_state=0.02, asp=None, offline_mode=False, 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)\n", + " Returns figure for county choropleth. Uses data from package_data.\n", + " \n", + " :param (list) fips: list of FIPS values which correspond to the con\n", + " catination of state and county ids. An example is '01001'.\n", + " :param (list) values: list of numbers/strings which correspond to the\n", + " fips list. These are the values that will determine how the counties\n", + " are colored.\n", + " :param (list) scope: list of states and/or states abbreviations. Fits\n", + " all states in the camera tightly. Selecting ['usa'] is the equivalent\n", + " of appending all 50 states into your scope list. Selecting only 'usa'\n", + " does not include 'Alaska', 'Puerto Rico', 'American Samoa',\n", + " 'Commonwealth of the Northern Mariana Islands', 'Guam',\n", + " 'United States Virgin Islands'. These must be added manually to the\n", + " list.\n", + " Default = ['usa']\n", + " :param (list) binning_endpoints: ascending numbers which implicitly define\n", + " real number intervals which are used as bins. The colorscale used must\n", + " have the same number of colors as the number of bins and this will\n", + " result in a categorical colormap.\n", + " :param (list) colorscale: a list of colors with length equal to the\n", + " number of categories of colors. The length must match either all\n", + " unique numbers in the 'values' list or if endpoints is being used, the\n", + " number of categories created by the endpoints.\n", + " \n", + " For example, if binning_endpoints = [4, 6, 8], then there are 4 bins:\n", + " [-inf, 4), [4, 6), [6, 8), [8, inf)\n", + " :param (list) order: a list of the unique categories (numbers/bins) in any\n", + " desired order. This is helpful if you want to order string values to\n", + " a chosen colorscale.\n", + " :param (float) simplify_county: determines the simplification factor\n", + " for the counties. The larger the number, the fewer vertices and edges\n", + " each polygon has. See\n", + " http://toblerity.org/shapely/manual.html#object.simplify for more\n", + " information.\n", + " Default = 0.02\n", + " :param (float) simplify_state: simplifies the state outline polygon.\n", + " See http://toblerity.org/shapely/manual.html#object.simplify for more\n", + " information.\n", + " Default = 0.02\n", + " :param (float) asp: the width-to-height aspect ratio for the camera.\n", + " Default = 2.5\n", + " :param (bool) offline_mode: if set to True, the centroids of each county\n", + " are invisible until selected over with a dragbox. Warning: this can\n", + " only be used if you are plotting in offline mode with validate set to\n", + " False as the params that are being added to the fig dictionary are not\n", + " yet part of the plotly.py python library. Stay tuned for updates.\n", + " Default = False\n", + " :param (bool) show_hover: show county hover and centroid info\n", + " :param (bool) show_state_data: reveals state boundary lines\n", + " :param (dict) state_outline: dict of attributes of the state outline\n", + " including width and color. See\n", + " https://plot.ly/python/reference/#scatter-marker-line for all valid\n", + " params\n", + " :param (dict) county_outline: dict of attributes of the county outline\n", + " including width and color. See\n", + " https://plot.ly/python/reference/#scatter-marker-line for all valid\n", + " params\n", + " :param (dict) centroid_marker: dict of attributes of the centroid marker.\n", + " See https://plot.ly/python/reference/#scatter-marker for all valid\n", + " params\n", + " :param (bool) round_legend_values: automatically round the numbers that\n", + " appear in the legend to the nearest integer.\n", + " Default = False\n", + " :param (bool) exponent_format: if set to True, puts numbers in the K, M,\n", + " B number format. For example 4000.0 becomes 4.0K\n", + " Default = False\n", + " :param (str) legend_title: title that appears above the legend\n", + " :param **layout_options: a **kwargs argument for all layout parameters\n", + " \n", + " \n", + " Example 1: Florida\n", + " ```\n", + " import plotly.plotly as py\n", + " import plotly.figure_factory as ff\n", + " \n", + " import numpy as np\n", + " import pandas as pd\n", + " \n", + " df_sample = pd.read_csv(\n", + " 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'\n", + " )\n", + " df_sample_r = df_sample[df_sample['STNAME'] == 'Florida']\n", + " \n", + " values = df_sample_r['TOT_POP'].tolist()\n", + " fips = df_sample_r['FIPS'].tolist()\n", + " \n", + " binning_endpoints = list(np.mgrid[min(values):max(values):4j])\n", + " colorscale = [\"#030512\",\"#1d1d3b\",\"#323268\",\"#3d4b94\",\"#3e6ab0\",\n", + " \"#4989bc\",\"#60a7c7\",\"#85c5d3\",\"#b7e0e4\",\"#eafcfd\"]\n", + " fig = ff.create_choropleth(\n", + " fips=fips, values=values, scope=['Florida'], show_state_data=True,\n", + " colorscale=colorscale, binning_endpoints=binning_endpoints,\n", + " round_legend_values=True, plot_bgcolor='rgb(229,229,229)',\n", + " paper_bgcolor='rgb(229,229,229)', legend_title='Florida Population',\n", + " county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n", + " exponent_format=True,\n", + " )\n", + " py.iplot(fig, filename='choropleth_florida')\n", + " ```\n", + " \n", + " Example 2: New England\n", + " ```\n", + " import plotly.plotly as py\n", + " import plotly.figure_factory as ff\n", + " \n", + " import pandas as pd\n", + " \n", + " NE_states = ['Connecticut', 'Maine', 'Massachusetts',\n", + " 'New Hampshire', 'Rhode Island']\n", + " df_sample = pd.read_csv(\n", + " 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'\n", + " )\n", + " df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)]\n", + " colorscale = ['rgb(68.0, 1.0, 84.0)',\n", + " 'rgb(66.0, 64.0, 134.0)',\n", + " 'rgb(38.0, 130.0, 142.0)',\n", + " 'rgb(63.0, 188.0, 115.0)',\n", + " 'rgb(216.0, 226.0, 25.0)']\n", + " \n", + " values = df_sample_r['TOT_POP'].tolist()\n", + " fips = df_sample_r['FIPS'].tolist()\n", + " fig = ff.create_choropleth(\n", + " fips=fips, values=values, scope=NE_states, show_state_data=True\n", + " )\n", + " py.iplot(fig, filename='choropleth_new_england')\n", + " ```\n", + " \n", + " Example 3: California and Surrounding States\n", + " ```\n", + " import plotly.plotly as py\n", + " import plotly.figure_factory as ff\n", + " \n", + " import pandas as pd\n", + " \n", + " df_sample = pd.read_csv(\n", + " 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'\n", + " )\n", + " df_sample_r = df_sample[df_sample['STNAME'] == 'California']\n", + " \n", + " values = df_sample_r['TOT_POP'].tolist()\n", + " fips = df_sample_r['FIPS'].tolist()\n", + " \n", + " colorscale = [\n", + " 'rgb(193, 193, 193)',\n", + " 'rgb(239,239,239)',\n", + " 'rgb(195, 196, 222)',\n", + " 'rgb(144,148,194)',\n", + " 'rgb(101,104,168)',\n", + " 'rgb(65, 53, 132)'\n", + " ]\n", + " \n", + " fig = ff.create_choropleth(\n", + " fips=fips, values=values, colorscale=colorscale,\n", + " scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'],\n", + " binning_endpoints=[14348, 63983, 134827, 426762, 2081313],\n", + " county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n", + " legend_title='California Counties',\n", + " title='California and Nearby States'\n", + " )\n", + " py.iplot(fig, filename='choropleth_california_and_surr_states_outlines')\n", + " ```\n", + " \n", + " Example 4: USA\n", + " ```\n", + " import plotly.plotly as py\n", + " import plotly.figure_factory as ff\n", + " \n", + " import numpy as np\n", + " import pandas as pd\n", + " \n", + " df_sample = pd.read_csv(\n", + " 'https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv'\n", + " )\n", + " df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(\n", + " lambda x: str(x).zfill(2)\n", + " )\n", + " df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(\n", + " lambda x: str(x).zfill(3)\n", + " )\n", + " df_sample['FIPS'] = (\n", + " df_sample['State FIPS Code'] + df_sample['County FIPS Code']\n", + " )\n", + " \n", + " binning_endpoints = list(np.linspace(1, 12, len(colorscale) - 1))\n", + " colorscale = [\"#f7fbff\", \"#ebf3fb\", \"#deebf7\", \"#d2e3f3\", \"#c6dbef\",\n", + " \"#b3d2e9\", \"#9ecae1\", \"#85bcdb\", \"#6baed6\", \"#57a0ce\",\n", + " \"#4292c6\", \"#3082be\", \"#2171b5\", \"#1361a9\", \"#08519c\",\n", + " \"#0b4083\",\"#08306b\"]\n", + " fips = df_sample['FIPS']\n", + " values = df_sample['Unemployment Rate (%)']\n", + " fig = ff.create_choropleth(\n", + " fips=fips, values=values, scope=['usa'],\n", + " binning_endpoints=binning_endpoints, colorscale=colorscale,\n", + " show_hover=True, centroid_marker={'opacity': 0},\n", + " asp=2.9, title='USA by Unemployment %',\n", + " legend_title='Unemployment %'\n", + " )\n", + " \n", + " py.iplot(fig, filename='choropleth_full_usa')\n", + " ```\n", + "\n" + ] + } + ], + "source": [ + "help(ff.create_choropleth)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Collecting git+https://github.com/plotly/publisher.git\n", + " Cloning https://github.com/plotly/publisher.git to /private/var/folders/tc/bs9g6vrd36q74m5t8h9cgphh0000gn/T/pip-9qabVC-build\n", + "Installing collected packages: publisher\n", + " Found existing installation: publisher 0.11\n", + " Uninstalling publisher-0.11:\n", + " Successfully uninstalled publisher-0.11\n", + " Running setup.py install for publisher ... \u001b[?25ldone\n", + "\u001b[?25hSuccessfully installed publisher-0.11\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning:\n", + "\n", + "The `IPython.nbconvert` package has been deprecated since IPython 4.0. You should import from nbconvert instead.\n", + "\n", + "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning:\n", + "\n", + "Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", + "\n" + ] + } + ], + "source": [ + "from IPython.display import display, HTML\n", + "\n", + "display(HTML(''))\n", + "display(HTML(''))\n", + "\n", + "! pip install git+https://github.com/plotly/publisher.git --upgrade\n", + "import publisher\n", + "publisher.publish(\n", + " 'county_choropleth.ipynb', 'python/county-choropleth/', 'USA County Choropleth Maps',\n", + " 'How to create colormaped representations of USA counties by FIPS values in Python.',\n", + " title = 'Python USA County Choropleth Maps | Plotly',\n", + " has_thumbnail='true', thumbnail='thumbnail/county-choropleth-usa-greybkgd.jpg', \n", + " language='python', page_type='example_index',\n", + " display_as='maps', order=0,\n", + " uses_plotly_offline=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 2", + "language": "python", + "name": "python2" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.12" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/_posts/python/maps/lines-on-maps/2015-06-30-lines_on_maps.html b/_posts/python/maps/lines-on-maps/2015-06-30-lines_on_maps.html index 5f69432dfb31..0f0134558188 100644 --- a/_posts/python/maps/lines-on-maps/2015-06-30-lines_on_maps.html +++ b/_posts/python/maps/lines-on-maps/2015-06-30-lines_on_maps.html @@ -15,24 +15,22 @@ ipynb: ~notebook_demo/58 --- {% raw %} -
-
+
-

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer. +

New to Plotly?¶

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!

-
-
+
-

US Flight Paths Map

+

US Flight Paths Map¶

@@ -108,7 +106,11 @@

US Flight Paths Map -
Out[1]:
+
+ +
Out[1]:
+ +
@@ -120,12 +122,11 @@

US Flight Paths Map -
+
-

London to NYC Great Circle

+

London to NYC Great Circle¶

@@ -186,7 +187,11 @@

London to NYC Great Circle -
Out[2]:
+
+ +
Out[2]:
+ +
@@ -198,12 +203,11 @@

London to NYC Great Circle -
+
-

Contour lines on globe

+

Contour lines on globe¶

@@ -294,7 +298,11 @@

Contour lines on globe -
Out[7]:
+
+ +
Out[7]:
+ +
-
-
+
-

Reference

See https://plot.ly/python/reference/#scattergeo for more information and chart attribute options!

+

Reference¶

See https://plot.ly/python/reference/#scattergeo for more information and chart attribute options!

-
{% endraw %} \ No newline at end of file +
+ + +{% endraw %} \ No newline at end of file diff --git a/_posts/python/maps/lines-on-maps/lines_on_maps.ipynb b/_posts/python/maps/lines-on-maps/lines_on_maps.ipynb index c85636ac7192..b9e915bfbebe 100644 --- a/_posts/python/maps/lines-on-maps/lines_on_maps.ipynb +++ b/_posts/python/maps/lines-on-maps/lines_on_maps.ipynb @@ -20,9 +20,7 @@ { "cell_type": "code", "execution_count": 1, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "data": { @@ -108,9 +106,7 @@ { "cell_type": "code", "execution_count": 2, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "data": { @@ -181,9 +177,7 @@ { "cell_type": "code", "execution_count": 7, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "data": { @@ -288,7 +282,6 @@ "cell_type": "code", "execution_count": 1, "metadata": { - "collapsed": false, "scrolled": true }, "outputs": [ @@ -321,22 +314,22 @@ "output_type": "stream", "text": [ "Collecting git+https://github.com/plotly/publisher.git\n", - " Cloning https://github.com/plotly/publisher.git to /var/folders/ld/6cl3s_l50wd40tdjq2b03jxh0000gp/T/pip-vxcBvr-build\n", + " Cloning https://github.com/plotly/publisher.git to /private/var/folders/tc/bs9g6vrd36q74m5t8h9cgphh0000gn/T/pip-Quuo1K-build\n", "Installing collected packages: publisher\n", - " Found existing installation: publisher 0.10\n", - " Uninstalling publisher-0.10:\n", - " Successfully uninstalled publisher-0.10\n", - " Running setup.py install for publisher ... \u001b[?25l-\b \b\\\b \bdone\n", - "\u001b[?25hSuccessfully installed publisher-0.10\n" + " Found existing installation: publisher 0.11\n", + " Uninstalling publisher-0.11:\n", + " Successfully uninstalled publisher-0.11\n", + " Running setup.py install for publisher ... \u001b[?25ldone\n", + "\u001b[?25hSuccessfully installed publisher-0.11\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ - "/Users/brandendunbar/Desktop/test/venv/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning: The `IPython.nbconvert` package has been deprecated. You should import from nbconvert instead.\n", + "/Library/Frameworks/Python.framework/Versions/2.7/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.\n", " \"You should import from nbconvert instead.\", ShimWarning)\n", - "/Users/brandendunbar/Desktop/test/venv/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning: Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", + "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning: Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", " warnings.warn('Did you \"Save\" this notebook before running this command? '\n" ] } @@ -387,9 +380,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", - "version": "2.7.10" + "version": "2.7.12" } }, "nbformat": 4, - "nbformat_minor": 0 + "nbformat_minor": 1 } diff --git a/_posts/python/maps/county-level-choropleth/2015-06-30-county-level-choropleth.html b/_posts/python/maps/mapbox-county-choropleth/2015-06-30-mapbox-county-choropleth.html similarity index 82% rename from _posts/python/maps/county-level-choropleth/2015-06-30-county-level-choropleth.html rename to _posts/python/maps/mapbox-county-choropleth/2015-06-30-mapbox-county-choropleth.html index bef22447e4a4..50ebd31152ad 100644 --- a/_posts/python/maps/county-level-choropleth/2015-06-30-county-level-choropleth.html +++ b/_posts/python/maps/mapbox-county-choropleth/2015-06-30-mapbox-county-choropleth.html @@ -1,13 +1,13 @@ --- -permalink: python/county-level-choropleth/ -description: How to make a Choropleth Map of Florida in Python with Plotly. -name: Python County Level Choropleth | plotly +permalink: python/mapbox-county-choropleth +description: How to make a Mapbox Choropleth Map of the Florida Counties in Python with Plotly. +name: Python Mapbox Choropleth Maps | plotly has_thumbnail: true thumbnail: thumbnail/county-level-choropleth.jpg layout: user-guide -name: County Level Choropleth +name: Mapbox Choropleth Maps language: python -title: Python County Level Choropleth | plotly +title: Python Mapbox Choropleth Maps | plotly display_as: maps has_thumbnail: true ipynb: ~notebook_demo/56 @@ -15,24 +15,22 @@ page_type: u-guide --- {% raw %} -
-
+
-

New to Plotly?

Plotly's Python library is free and open source! Get started by dowloading the client and reading the primer. +

New to Plotly?¶

Plotly's Python library is free and open source! Get started by dowloading 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!

-
-
+
-

Version Check

Run pip install plotly --upgrade to update your Plotly version

+

Version Check¶

Run pip install plotly --upgrade to update your Plotly version

@@ -54,11 +52,15 @@

Version Check - -
-
+
-
-
+
-

Mapbox Access Token

+

Mapbox Access Token¶

-
-
+
@@ -96,17 +95,15 @@

Mapbox Access Token -
+ -
-
+
@@ -117,7 +114,7 @@

Read the Data -
-
-
-
-
-

Since we want to separate the counties into Republican and Democratic for the seperate coloring, and since the county names in the GeoJSON are fuller text descriptions of each county on the website, we need to parse through and convert the names in the GeoJSON to the website format

- -
-
-
-
-
-
In [3]:
-
-
- -
-
- - -
-
-
['Charlotte', 'Seminole', 'Baker', 'DeSoto', 'Levy', 'Alachua', 'Pasco', 'Hendry', 'Okeechobee', 'Broward', 'St. Johns', 'Gulf', 'Glades', 'Marion', 'Duval', 'Madison', 'Osceola', 'Lee', 'Volusia', 'Sarasota', 'Indian River', 'Clay', 'Putnam', 'Wakulla', 'Holmes', 'Escambia', 'Flagler', 'Union', 'Brevard', 'Suwannee', 'Orange', 'Martin', 'Nassau', 'Jefferson', 'Santa Rosa', 'Hamilton', 'Calhoun', 'Hernando', 'Miami-Dade', 'Pinellas', 'Palm Beach', 'Hillsborough', 'Collier', 'Gilchrist', 'Dixie', 'Bay', 'Gadsden', 'Okaloosa', 'Citrus', 'Lafayette', 'Manatee', 'Monroe', 'Columbia', 'Sumter', 'Washington', 'St. Lucie', 'Polk', 'Taylor', 'Leon', 'Lake', 'Highlands', 'Hardee', 'Bradford', 'Liberty', 'Franklin', 'Walton', 'Jackson']
-
+
+
+
+

Since we want to separate the counties into Republican and Democratic for the seperate coloring, and since the county names in the GeoJSON are fuller text descriptions of each county on the website, we need to parse through and convert the names in the GeoJSON to the website format

-
-
-
+ -
-
+
@@ -254,17 +220,15 @@

Color the Counties -
+
-

Create JSON Files

+

Create JSON Files¶

-
-
+
@@ -295,8 +259,7 @@

Create JSON Files -
+
@@ -365,7 +328,11 @@

Create JSON Files -
Out[6]:
+
+ +
Out[6]:
+ +
@@ -377,13 +344,15 @@

Create JSON Files -
+
-

Reference

See https://plot.ly/python/reference/#scattermapbox for more information about mapbox and their attribute options.

+

Reference¶

See https://plot.ly/python/reference/#scattermapbox for more information about mapbox and their attribute options.

-
{% endraw %} \ No newline at end of file +
+ + +{% endraw %} \ No newline at end of file diff --git a/_posts/python/maps/county-level-choropleth/florida-blue-data.json b/_posts/python/maps/mapbox-county-choropleth/florida-blue-data.json similarity index 100% rename from _posts/python/maps/county-level-choropleth/florida-blue-data.json rename to _posts/python/maps/mapbox-county-choropleth/florida-blue-data.json diff --git a/_posts/python/maps/county-level-choropleth/florida-red-data.json b/_posts/python/maps/mapbox-county-choropleth/florida-red-data.json similarity index 100% rename from _posts/python/maps/county-level-choropleth/florida-red-data.json rename to _posts/python/maps/mapbox-county-choropleth/florida-red-data.json diff --git a/_posts/python/maps/county-level-choropleth/county-level-choropleth.ipynb b/_posts/python/maps/mapbox-county-choropleth/mapbox-county-choropleth.ipynb similarity index 89% rename from _posts/python/maps/county-level-choropleth/county-level-choropleth.ipynb rename to _posts/python/maps/mapbox-county-choropleth/mapbox-county-choropleth.ipynb index d11d38191b25..5f0ff66a5fb1 100644 --- a/_posts/python/maps/county-level-choropleth/county-level-choropleth.ipynb +++ b/_posts/python/maps/mapbox-county-choropleth/mapbox-county-choropleth.ipynb @@ -26,7 +26,7 @@ { "data": { "text/plain": [ - "'2.0.6'" + "'2.4.1'" ] }, "execution_count": 1, @@ -76,8 +76,10 @@ }, { "cell_type": "code", - "execution_count": 2, - "metadata": {}, + "execution_count": 5, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "import urllib\n", @@ -87,34 +89,9 @@ "import json\n", "\n", "url = 'http://catalog.civicdashboards.com/dataset/cda82e8b-7a8b-411e-95ba-1200b921c35d/resource/5c5d19a0-b817-49e6-b76e-ea63a8e2c0f6/download/fd880c1e4d23463ca869f1122109b3eftemp.geojson'\n", - "florida_data = urllib.urlopen(url).read()\n", - "florida_data = ast.literal_eval(florida_data)\n", - "\n", "repub_democ_counties_url = 'http://dos.myflorida.com/elections/data-statistics/voter-registration-statistics/voter-registration-monthly-reports/voter-registration-current-by-county/'\n", - "repub_democ_counties = urllib.urlopen(repub_democ_counties_url).read()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Since we want to separate the counties into Republican and Democratic for the seperate coloring, and since the county names in the GeoJSON are fuller text descriptions of each county on the website, we need to parse through and convert the names in the GeoJSON to the website format" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['Charlotte', 'Seminole', 'Baker', 'DeSoto', 'Levy', 'Alachua', 'Pasco', 'Hendry', 'Okeechobee', 'Broward', 'St. Johns', 'Gulf', 'Glades', 'Marion', 'Duval', 'Madison', 'Osceola', 'Lee', 'Volusia', 'Sarasota', 'Indian River', 'Clay', 'Putnam', 'Wakulla', 'Holmes', 'Escambia', 'Flagler', 'Union', 'Brevard', 'Suwannee', 'Orange', 'Martin', 'Nassau', 'Jefferson', 'Santa Rosa', 'Hamilton', 'Calhoun', 'Hernando', 'Miami-Dade', 'Pinellas', 'Palm Beach', 'Hillsborough', 'Collier', 'Gilchrist', 'Dixie', 'Bay', 'Gadsden', 'Okaloosa', 'Citrus', 'Lafayette', 'Manatee', 'Monroe', 'Columbia', 'Sumter', 'Washington', 'St. Lucie', 'Polk', 'Taylor', 'Leon', 'Lake', 'Highlands', 'Hardee', 'Bradford', 'Liberty', 'Franklin', 'Walton', 'Jackson']\n" - ] - } - ], - "source": [ + "repub_democ_counties = urllib.urlopen(repub_democ_counties_url).read()\n", + "\n", "county_names = []\n", "county_names_dict = {}\n", "\n", @@ -127,6 +104,13 @@ "print county_names" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since we want to separate the counties into Republican and Democratic for the seperate coloring, and since the county names in the GeoJSON are fuller text descriptions of each county on the website, we need to parse through and convert the names in the GeoJSON to the website format" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -144,7 +128,9 @@ { "cell_type": "code", "execution_count": 4, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "red_counties = []\n", @@ -204,7 +190,9 @@ { "cell_type": "code", "execution_count": 5, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "red_data = {\"type\": \"FeatureCollection\"}\n", @@ -349,10 +337,10 @@ "\n", "import publisher\n", "publisher.publish(\n", - " 'county-level-choropleth.ipynb', 'python/county-level-choropleth/', 'Python County Level Choropleth | plotly',\n", - " 'How to make a Choropleth Map of Florida in Python with Plotly.',\n", - " title='Python County Level Choropleth | plotly',\n", - " name='County Level Choropleth',\n", + " 'mapbox-county-choropleth.ipynb', 'python/mapbox-county-choropleth', 'Python Mapbox Choropleth Maps | plotly',\n", + " 'How to make a Mapbox Choropleth Map of the Florida Counties in Python with Plotly.',\n", + " title='Python Mapbox Choropleth Maps | plotly',\n", + " name='Mapbox Choropleth Maps',\n", " thumbnail='thumbnail/county-level-choropleth.jpg', language='python',\n", " has_thumbnail='true', display_as='maps', order=1.5,\n", " ipynb= '~notebook_demo/56')" @@ -384,7 +372,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", - "version": "2.7.11" + "version": "2.7.12" } }, "nbformat": 4, diff --git a/_posts/python/maps/mapbox/2015-06-30-mapbox.html b/_posts/python/maps/mapbox/2015-06-30-mapbox.html index 9572aadf4d53..2ee0a70c008f 100644 --- a/_posts/python/maps/mapbox/2015-06-30-mapbox.html +++ b/_posts/python/maps/mapbox/2015-06-30-mapbox.html @@ -19,7 +19,7 @@

-

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer. +

New to Plotly?¶

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!

@@ -30,7 +30,7 @@

New to Plotly?
-

Version Check

Plotly's Python package is updated frequently. Run pip install plotly --upgrade to make sure you're using the latest version.

+

Version Check¶

Plotly's Python package is updated frequently. Run pip install plotly --upgrade to make sure you're using the latest version.

@@ -73,7 +73,7 @@

Version Check
-

Mapbox Access Token

To plot on Mapbox maps with Plotly you'll need a Mapbox account and a public Mapbox Access Token which you can add to your Plotly settings. If you're using a Plotly On-Premise server, please see additional instructions here: https://help.plot.ly/mapbox-atlas/.

+

Mapbox Access Token¶

To plot on Mapbox maps with Plotly you'll need a Mapbox account and a public Mapbox Access Token which you can add to your Plotly settings. If you're using a Plotly On-Premise server, please see additional instructions here: https://help.plot.ly/mapbox-atlas/.

@@ -82,7 +82,7 @@

Mapbox Access Token
-

Basic Example

+

Basic Example¶

@@ -155,7 +155,7 @@

Basic Example
-

Multiple Markers

+

Multiple Markers¶

@@ -239,7 +239,7 @@

Multiple Markers
-

Nuclear Waste Sites on Campuses

+

Nuclear Waste Sites on Campuses¶

@@ -336,7 +336,7 @@

Nuclear Waste Sites on Campuses
-

Reference

See https://plot.ly/python/reference/#scattermapbox for more information and options!

+

Reference¶

See https://plot.ly/python/reference/#scattermapbox for more information and options!

diff --git a/_posts/python/maps/mapbox/mapbox.ipynb b/_posts/python/maps/mapbox/mapbox.ipynb index d529bb00e821..6177acb21350 100644 --- a/_posts/python/maps/mapbox/mapbox.ipynb +++ b/_posts/python/maps/mapbox/mapbox.ipynb @@ -282,7 +282,7 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 1, "metadata": {}, "outputs": [ { @@ -313,14 +313,10 @@ "name": "stderr", "output_type": "stream", "text": [ - "/Users/chelsea/venv/venv2.7/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning:\n", - "\n", - "The `IPython.nbconvert` package has been deprecated since IPython 4.0. You should import from nbconvert instead.\n", - "\n", - "/Users/chelsea/venv/venv2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning:\n", - "\n", - "Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", - "\n" + "/Library/Frameworks/Python.framework/Versions/2.7/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.\n", + " \"You should import from nbconvert instead.\", ShimWarning)\n", + "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning: Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", + " warnings.warn('Did you \"Save\" this notebook before running this command? '\n" ] } ], @@ -370,7 +366,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", - "version": "2.7.10" + "version": "2.7.12" } }, "nbformat": 4,