{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### New to Plotly?\n",
"Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).\n",
"
You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/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!\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Version Check\n",
"Plotly's python package is updated frequently. Run `pip install plotly --upgrade` to use the latest version."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'3.6.1'"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly\n",
"plotly.__version__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### United States Choropleth Map"
]
},
{
"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.graph_objs as go\n",
"\n",
"import pandas as pd\n",
"\n",
"df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')\n",
"\n",
"for col in df.columns:\n",
" df[col] = df[col].astype(str)\n",
"\n",
"scl = [\n",
" [0.0, 'rgb(242,240,247)'],\n",
" [0.2, 'rgb(218,218,235)'],\n",
" [0.4, 'rgb(188,189,220)'],\n",
" [0.6, 'rgb(158,154,200)'],\n",
" [0.8, 'rgb(117,107,177)'],\n",
" [1.0, 'rgb(84,39,143)']\n",
"]\n",
"\n",
"df['text'] = df['state'] + '
' + \\\n",
" 'Beef ' + df['beef'] + ' Dairy ' + df['dairy'] + '
' + \\\n",
" 'Fruits ' + df['total fruits'] + ' Veggies ' + df['total veggies'] + '
' + \\\n",
" 'Wheat ' + df['wheat'] + ' Corn ' + df['corn']\n",
"\n",
"data = [go.Choropleth(\n",
" colorscale = scl,\n",
" autocolorscale = False,\n",
" locations = df['code'],\n",
" z = df['total exports'].astype(float),\n",
" locationmode = 'USA-states',\n",
" text = df['text'],\n",
" marker = go.choropleth.Marker(\n",
" line = go.choropleth.marker.Line(\n",
" color = 'rgb(255,255,255)',\n",
" width = 2\n",
" )),\n",
" colorbar = go.choropleth.ColorBar(\n",
" title = \"Millions USD\")\n",
")]\n",
"\n",
"layout = go.Layout(\n",
" title = go.layout.Title(\n",
" text = '2011 US Agriculture Exports by State
(Hover for breakdown)'\n",
" ),\n",
" geo = go.layout.Geo(\n",
" scope = 'usa',\n",
" projection = go.layout.geo.Projection(type = 'albers usa'),\n",
" showlakes = True,\n",
" lakecolor = 'rgb(255, 255, 255)'),\n",
")\n",
"\n",
"fig = go.Figure(data = data, layout = layout)\n",
"py.iplot(fig, filename = 'd3-cloropleth-map')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### World Choropleth Map"
]
},
{
"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 pandas as pd\n",
"\n",
"df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')\n",
"\n",
"data = [go.Choropleth(\n",
" locations = df['CODE'],\n",
" z = df['GDP (BILLIONS)'],\n",
" text = df['COUNTRY'],\n",
" colorscale = [\n",
" [0, \"rgb(5, 10, 172)\"],\n",
" [0.35, \"rgb(40, 60, 190)\"],\n",
" [0.5, \"rgb(70, 100, 245)\"],\n",
" [0.6, \"rgb(90, 120, 245)\"],\n",
" [0.7, \"rgb(106, 137, 247)\"],\n",
" [1, \"rgb(220, 220, 220)\"]\n",
" ],\n",
" autocolorscale = False,\n",
" reversescale = True,\n",
" marker = go.choropleth.Marker(\n",
" line = go.choropleth.marker.Line(\n",
" color = 'rgb(180,180,180)',\n",
" width = 0.5\n",
" )),\n",
" colorbar = go.choropleth.ColorBar(\n",
" tickprefix = '$',\n",
" title = 'GDP
Billions US$'),\n",
")]\n",
"\n",
"layout = go.Layout(\n",
" title = go.layout.Title(\n",
" text = '2014 Global GDP'\n",
" ),\n",
" geo = go.layout.Geo(\n",
" showframe = False,\n",
" showcoastlines = False,\n",
" projection = go.layout.geo.Projection(\n",
" type = 'equirectangular'\n",
" )\n",
" ),\n",
" annotations = [go.layout.Annotation(\n",
" x = 0.55,\n",
" y = 0.1,\n",
" xref = 'paper',\n",
" yref = 'paper',\n",
" text = 'Source: \\\n",
" CIA World Factbook',\n",
" showarrow = False\n",
" )]\n",
")\n",
"\n",
"fig = go.Figure(data = data, layout = layout)\n",
"py.iplot(fig, filename = 'd3-world-map')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Choropleth Inset Map"
]
},
{
"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.graph_objs as go\n",
"\n",
"import pandas as pd\n",
"df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_ebola.csv')\n",
"df.head()\n",
"\n",
"cases = []\n",
"colors = ['rgb(239,243,255)','rgb(189,215,231)','rgb(107,174,214)','rgb(33,113,181)']\n",
"months = {6:'June',7:'July',8:'Aug',9:'Sept'}\n",
"\n",
"for i in range(6,10)[::-1]:\n",
" cases.append(go.Scattergeo(\n",
" lon = df[ df['Month'] == i ]['Lon'], #-(max(range(6,10))-i),\n",
" lat = df[ df['Month'] == i ]['Lat'],\n",
" text = df[ df['Month'] == i ]['Value'],\n",
" name = months[i],\n",
" marker = go.scattergeo.Marker(\n",
" size = df[ df['Month'] == i ]['Value']/50,\n",
" color = colors[i-6],\n",
" line = go.scattergeo.marker.Line(width = 0)\n",
" ),\n",
" ) )\n",
"\n",
"cases[0]['text'] = df[ df['Month'] == 9 ]['Value'].map('{:.0f}'.format).astype(str)+' '+\\\n",
" df[ df['Month'] == 9 ]['Country']\n",
"cases[0]['mode'] = 'markers+text'\n",
"cases[0]['textposition'] = 'bottom center'\n",
"\n",
"inset = [\n",
" go.Choropleth(\n",
" locationmode = 'country names',\n",
" locations = df[ df['Month'] == 9 ]['Country'],\n",
" z = df[ df['Month'] == 9 ]['Value'],\n",
" text = df[ df['Month'] == 9 ]['Country'],\n",
" colorscale = [[0,'rgb(0, 0, 0)'],[1,'rgb(0, 0, 0)']],\n",
" autocolorscale = False,\n",
" showscale = False,\n",
" geo = 'geo2'\n",
" ),\n",
" go.Scattergeo(\n",
" lon = [21.0936],\n",
" lat = [7.1881],\n",
" text = ['Africa'],\n",
" mode = 'text',\n",
" showlegend = False,\n",
" geo = 'geo2'\n",
" )\n",
"]\n",
"\n",
"layout = go.Layout(\n",
" title = go.layout.Title(\n",
" text = 'Ebola cases reported by month in West Africa 2014
\\\n",
"Source: \\\n",
"HDX'),\n",
" geo = go.layout.Geo(\n",
" resolution = 50,\n",
" scope = 'africa',\n",
" showframe = False,\n",
" showcoastlines = True,\n",
" showland = True,\n",
" landcolor = \"rgb(229, 229, 229)\",\n",
" countrycolor = \"rgb(255, 255, 255)\" ,\n",
" coastlinecolor = \"rgb(255, 255, 255)\",\n",
" projection = go.layout.geo.Projection(\n",
" type = 'equirectangular'\n",
" ),\n",
" lonaxis = go.layout.geo.Lonaxis(\n",
" range= [ -15.0, -5.0 ]\n",
" ),\n",
" lataxis = go.layout.geo.Lataxis(\n",
" range= [ 0.0, 12.0 ]\n",
" ),\n",
" domain = go.layout.geo.Domain(\n",
" x = [ 0, 1 ],\n",
" y = [ 0, 1 ]\n",
" )\n",
" ),\n",
" geo2 = go.layout.Geo(\n",
" scope = 'africa',\n",
" showframe = False,\n",
" showland = True,\n",
" landcolor = \"rgb(229, 229, 229)\",\n",
" showcountries = False,\n",
" domain = go.layout.geo.Domain(\n",
" x = [ 0, 0.6 ],\n",
" y = [ 0, 0.6 ]\n",
" ),\n",
" bgcolor = 'rgba(255, 255, 255, 0.0)',\n",
" ),\n",
" legend = go.layout.Legend(\n",
" traceorder = 'reversed'\n",
" )\n",
")\n",
"\n",
"fig = go.Figure(layout=layout, data=cases+inset)\n",
"py.iplot(fig, filename='West Africa Ebola cases 2014')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Full County Choropleths\n",
"For the full county choropleth doc page checkout https://plotly.com/python/county-choropleth/"
]
},
{
"cell_type": "code",
"execution_count": 6,
"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": 6,
"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",
"]\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 = {\n",
" 'opacity': 0\n",
" },\n",
" asp = 2.9,\n",
" title = 'USA by Unemployment %',\n",
" legend_title = '% unemployed'\n",
")\n",
"py.iplot(fig, filename = 'choropleth_full_usa')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dash Example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Dash](https://plotly.com/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-choroplethplot) can easily be deployed to a PaaS."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
" \n",
" "
],
"text/plain": [
""
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import IFrame\n",
"IFrame(src= \"https://dash-simple-apps.plotly.host/dash-choroplethplot/\", width=\"100%\", height=\"950px\", frameBorder=\"0\")"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
" \n",
" "
],
"text/plain": [
""
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import IFrame\n",
"IFrame(src= \"https://dash-simple-apps.plotly.host/dash-choroplethplot/code\", width=\"100%\", height=500, frameBorder=\"0\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Reference\n",
"See https://plotly.com/python/reference/#choropleth for more information and chart attribute options!"
]
},
{
"cell_type": "code",
"execution_count": 3,
"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/s5/vjqn03zs7nn8zs_fwzcf14r40000gn/T/pip-req-build-yyuryex2\n",
"Building wheels for collected packages: publisher\n",
" Building wheel for publisher (setup.py) ... \u001b[?25ldone\n",
"\u001b[?25h Stored in directory: /private/var/folders/s5/vjqn03zs7nn8zs_fwzcf14r40000gn/T/pip-ephem-wheel-cache-m3irlu81/wheels/99/3e/a0/fbd22ba24cca72bdbaba53dbc23c1768755fb17b3af0f33966\n",
"Successfully built publisher\n",
"Installing collected packages: publisher\n",
" Found existing installation: publisher 0.13\n",
" Uninstalling publisher-0.13:\n",
" Successfully uninstalled publisher-0.13\n",
"Successfully installed publisher-0.13\n",
"\u001b[33mYou are using pip version 19.0.3, however version 19.1.1 is available.\n",
"You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\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",
" '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',\n",
" display_as='maps', order=1, ipynb='~notebook_demo/55')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}