Choropleth in Plotly python for USA is Blank - python

import os
import seaborn as sns
print(os.listdir("../input"))
df=pd.read_csv("../input/gun-violence-data_01-2013_03-2018.csv")
//GUN
violence dataset from kaggle//
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
import plotly.graph_objs as go
b=df.state.value_counts().sort_values()
ba=pd.DataFrame(b)
ans=ba.reset_index(inplace=True)
//creating a dataframe only containing the state names of USA and its count//
data = [ dict(type='choropleth',
autocolorscale = False,
locations = ba['index'],
z = ba['state'],
locationmode = 'USA-states',
text = ba['index'],
colorscale='Viridis' ) ]
layout = dict(
title = 'US',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 165, 255)'),)
fig = go.Figure( data=data,layout=layout )
iplot(fig)
However, whenever I run this code, Only a blank image of USA is obtained,
which is blank and shows no values. please help!

Related

Not able to view US-states heatmap

I have written the following code to heat heatmap of US-States. But I am unable to get the output image in Google Colab.
State codes are two alphabet codes for a particular state of the US.
temp = pd.DataFrame(project_data.groupby("school_state")["project_is_approved"].apply(np.mean)).reset_index()
temp.columns = ['state_code', 'num_proposals']
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = temp['state_code'],
z = temp['num_proposals'].astype(float),
locationmode = 'USA-states',
text = temp['state_code'],
marker = dict(line = dict (color = 'rgb(255,255,255)',width = 2)),
colorbar = dict(title = "% of pro")
) ]
layout = dict(
title = 'Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
offline.iplot(fig, filename='us-map-heat-map')
I have imported following libraries:
from chart_studio import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
import chart_studio.plotly as py
Try the following code with your data:
(I tried putting your variables in the correct spots)
choropleth = go.Choropleth(
locations=temp['state_code'],
locationmode='USA-states',
z = temp['num_proposals'].astype(float),
zmin = 0,
zmax = max(temp['num_proposals'].astype(float)),
colorscale=scl,
autocolorscale=False,
text='Proposals',
marker_line_color='white',
colorbar_title="% Acceptance Rate"
)
fig = go.Figure(data=choropleth)
fig.update_layout(
title_text='Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True,
lakecolor='rgb(255, 255, 255)'),
)
fig.show()
This code works by creating the Plotly Choropleth Graph Object with your data, then loading that object into a Plotly Figure Graph Object, then updating the layout (for proper titles and zooms), and finally displaying the figure.

Interactive plot with Slider using Plotly

How do I recreate the following interactive plot in Python using Plotly?
My simple example draws a bar chart with one column x and another 1-x.
GIF from Mathematica:
Slider allows for a varying x between 0 and 1.
Mathematica code:
Manipulate[BarChart[{x, 1 - x}, PlotRange -> {0, 1}],
{{x, 0.3, "Level"}, 0, 1, Appearance -> "Open"}]
UPDATE
Here is a solution which I don't like:
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
import ipywidgets as widgets
Plotting:
def update_plot(x):
data = [go.Bar(
x=['1', '2'],
y=[x, 1-x]
)]
iplot(data, show_link=False)
x = widgets.FloatSlider(min=0, max=1, value=0.3)
widgets.interactive(update_plot, x=x)
Problems with this:
The plot twinkles when the slider is moved
The slider is misplaced
The increment is not granular enough
I cannot specify a precise value myself
Code below creates an interactive plot in plotly and Dash. It takes two inputs: slider and text box. When the code below saved as a '.py' and the file is run in terminal, it should run a local server in the terminal. Next, copy the * Running on http:// address from this server and paste it in browser to open the plot. Most likely it would be http://127.0.0.1:8050/. Resources: 1, 2, 3 . (Python 3.6.6)
Important: Please note that for the slider to work, the text box value has to be reset to '0' (zero).
Import libraries
import numpy as np
import pandas as pd
from plotly import __version__
import plotly.offline as pyo
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
Create Dash app
app = dash.Dash()
app.layout = html.Div(
html.Div([
html.Div([html.H5("Level"),
dcc.Slider(id='slider_input',
min=0,
max=1,
step=0.005,
value=0.1,
)],style={'width': '200'}
),
html.Div(style={'height': '10'}),
html.Div(dcc.Input( id='text_input',
placeholder='Enter a value...',
type='text',
value=0.0
),style={'width': '50'}),
dcc.Graph(id='example',
figure={'data':[{'x':[1,2],
'y':[0,1],
'type':'bar',
'marker':dict(color='#ffbf00')
}],
'layout': go.Layout(title='Plot',
#xaxis = list(range = c(2, 5)),
yaxis=dict(range=[0, 1])
)
})
], style={'width':'500', 'height':'200','display':'inline-block'})
)
# callback - 1 (from slider)
#app.callback(Output('example', 'figure'),
[Input('slider_input', 'value'),
Input('text_input', 'value')])
def update_plot(slider_input, text_input):
if (float(text_input)==0.0):
q = float(slider_input)
else:
q = float(text_input)
figure = {'data': [go.Bar(x=[1,2],
y=[q, 1-q],
marker=dict(color='#ffbf00'),
width=0.5
)],
'layout': go.Layout(title='plot',
#xaxis = list(range = c(2, 5)),
yaxis=dict(range=[0, 1])
)
}
return figure
Run server
if __name__ == '__main__':
app.run_server()
Output
Edit - 1 .............................
Plot with slider only
The code below uses plotly without dash. The plot is interactive with a slider. Note that this code does not have a text input to change the plot (as above). However, the plot below should update with slider without the need to 'release' the slider to see the update. In this plot, individual traces were created for plotting.
Import libraries
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline
import json
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
init_notebook_mode(connected=True)
cf.go_offline()
Create traces
traces = []
q = np.linspace(0,1, 100)
for i in range(0,len(q)):
trace = dict(
type = 'bar',
visible = False,
x=[1, 2],
y=[q[i], 1 - q[i]],
marker=dict(color='#ffbf00'),
width=0.5
)
traces.append(trace)
traces[0]['visible'] = 'True'
Create slider
steps=[]
for i in range(len(traces)):
step = dict(
method = 'restyle',
args = ['visible', [False] * len(traces)],
label=""
)
step['args'][1][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(
active = 10,
currentvalue = {"prefix": "Level: "},
#pad = {"t": 50},
steps = steps
)]
Create layout
layout = go.Layout(
width=500,
height=500,
autosize=False,
yaxis=dict(range=[0, 1])
)
layout['sliders'] = sliders
Plot figure
fig = go.Figure(data=traces, layout=layout)
#pyo.iplot(fig, show_link=False) # run this line to view inline in Jupyter Notebook
pyo.plot(fig, show_link=False) # run this line to view in browser
Starting from Plotly 3.0 this can be achieved as follows (in JupyterLab):
import plotly.graph_objects as go
from ipywidgets import interact
fig = go.FigureWidget()
bar = fig.add_bar(x=['x', '1-x'])
fig.layout = dict(yaxis=dict(range=[0,1]), height=600)
#interact(x=(0, 1, 0.01))
def update(x=0.3):
with fig.batch_update():
bar.y=[x, 1-x]
fig
Update:
From Plotly 4.0 you need to specify fig.data[0].y instead of bar.y.

Choropleth map with plotly error: invalid figure_or_data argument

I'd like to use plotly to construct a choropleth map. I have a dataframe with the state codes and a count that looks like this:
count state
0 1 AK
1 9 AL
2 2 AR
3 11 AZ
4 31 CA
...
I've tried the following:
from plotly.offline import init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
test_data = [dict(type='choropleth',
autocolorscale=False,
locations=df['state'],
z=df['count'],
locationmode='USA-states',
marker=dict(
line=dict(
color='rgb(255,255,255)',
width=2
)),
colorbar=dict(
title='Choropleth Map Test')
)]
layout = dict(
title='Test title',
geo = dict(
scope='usa',
projection=dict(type='albers usa'),
snowflakes=True,
lakecolor='rgb(255,255,255)'),
)
fig = dict(data=data, layout=layout)
py.iplot(fig,filename='d3-cloropleth-map')
Then I get an error:
PlotlyDictValueError: 'data' has invalid value inside 'figure'
Path To Error: ['data']
Current path: []
Current parent object_names: []
Additionally:
role: object
During handling of the above exception, another exception occurred:
Can someone please point me in the right direction?
from plotly.offline import init_notebook_mode, plot, iplot
You've already imported iplot from plotly.offline and should call the function directly. Use iplot() instead of py.iplot().
py appears to be defined as something else that is not included in the code you've listed above.
Code below should work:
Import libraries
import pandas as pd
from plotly import __version__
%matplotlib inline
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.offline import iplot
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
init_notebook_mode(connected=True)
cf.go_offline()
Create sample data
state = ['AK', 'AL', 'AR', 'AZ', 'CA']
count = [1,9,2,11,31]
df = pd.DataFrame({'state':state, 'count':count})
df.head(2)
Code below is from the question above
Note: snowflakes=True is commented out
test_data = [dict(type='choropleth',
autocolorscale=False,
locations=df['state'],
z=df['count'],
locationmode='USA-states',
marker=dict(
line=dict(
color='rgb(255,255,255)',
width=2
)),
colorbar=dict(
title='Choropleth Map Test')
)]
layout = dict(
title='Test title',
geo = dict(
scope='usa',
projection=dict(type='albers usa'),
#snowflakes=True,
lakecolor='rgb(255,255,255)'),
)
fig = dict(data=test_data, layout=layout)
pyo.iplot(fig,filename='d3-cloropleth-map')
# Code works, but no MAP
Must Restart and run all
!pip install cufflinks
!pip install chart_studio
import chart_studio
import pandas as pd
from plotly import __version__
%matplotlib inline
import plotly.offline as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs
from plotly.offline import init_notebook_mode, plot, iplot
import cufflinks as cf
init_notebook_mode(connected=True)
cf.go_offline()
# scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
# [0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
#Create sample data
state = ['AK', 'AL', 'AR', 'AZ', 'CA']
count = [1,9,2,11,31]
df = pd.DataFrame({'state':state, 'count':count})
#df.head(2)
#Code below is from the question above
#Note: snowflakes=True is commented out
test_data = [dict(type='choropleth',
autocolorscale=False,
locations=df['state'],
z=df['count'],
locationmode='USA-states',
marker=dict(
line=dict(
color='rgb(255,255,255)',
width=2
)),
colorbar=dict(
title='Choropleth Map Test')
)]
layout = dict(
title='Test title',
geo = dict(
scope='usa',
projection=dict(type='albers usa'),
#snowflakes=True,
lakecolor='rgb(255,255,255)'),
)
fig = dict(data=test_data, layout=layout)
py.iplot(fig,filename='d3-cloropleth-map')
plotly could be the problem... try installing this way:
pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org plotly

Python Plotly Error

It seems that the example code on the plotly website for choropleth maps is out of date and no longer works.
The error I'm getting is:
PlotlyError: Invalid 'figure_or_data' argument. Plotly will not be able to properly parse the resulting JSON. If you want to send this 'figure_or_data' to Plotly anyway (not recommended), you can set 'validate=False' as a plot option.
Here's why you're seeing this error:
The entry at index, '0', is invalid because it does not contain a valid 'type' key-value. This is required for valid 'Data' lists.
Path To Error:
['data'][0]
The code that I'm trying to run is shown below. It is copied as-is from the plotly website. Anyone have any ideas as to how I can fix it?
import plotly.plotly as py
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
for col in df.columns:
df[col] = df[col].astype(str)
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
df['text'] = df['state'] + '<br>' +\
'Beef '+df['beef']+' Dairy '+df['dairy']+'<br>'+\
'Fruits '+df['total fruits']+' Veggies ' + df['total veggies']+'<br>'+\
'Wheat '+df['wheat']+' Corn '+df['corn']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)
),
colorbar = dict(
title = "Millions USD"
)
) ]
layout = dict(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
url = py.plot(fig, filename='d3-cloropleth-map')
fig should be of the Figure type. Use the Choropleth graph object:
import plotly.graph_objs as go
...
data = [go.Choropleth(
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict(
color = 'rgb(255,255,255)',
width = 2)),
colorbar = dict(
title = "Millions USD")
)]
...
fig = go.Figure(data=data, layout=layout)
...

ipython plotly map render on a django template

This is what I am doing in an ipython notebook where the plotly graphs and everything gets generated without fail. After that I am taking the html form of the notebook and embedding it in a django template where everything is working other than the plotly graphs. I am not sure what needs to be done thats why I also tried installing plotly on npm and also including a reference to plotly.js through my template. Below are the codes.
import pandas as pd
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
data = pd.read_csv("storage/AviationDataUp.csv")
useful_columns = ['Event.Date', 'Location', 'Country', 'Latitude', 'Longitude', 'Purpose.of.Flight',\
'Total.Fatal.Injuries','Number.of.Engines','Air.Carrier']
data = data[useful_columns]
data = data[data['Country']=='United States']
accident_trace = Scattergeo(
locationmode = 'ISO-3',
lon = data['Longitude'],
lat = data['Latitude'],
mode = 'markers',
marker = dict(
size = 2,
opacity = 0.75,
color="rgb(0, 130, 250)"),
name = 'Accidents'
)
layout = dict(
title = 'Aviation Accidents in USA',
geo = dict(
scope = 'usa',
projection = dict(),
showland = True,
landcolor = 'rgb(250, 250, 250)',
subunitwidth = 1,
subunitcolor = 'rgb(217, 217, 217)',
countrywidth = 1,
countrycolor = 'rgb(217, 217, 217)',
showlakes = True,
lakecolor = 'rgb(255, 255, 255)'
) )
figure = dict(data=Data([accident_trace]), layout=layout)
iplot(figure)

Categories