Error drawing a choropleth map with plotly - python

I'm new in Plotly. I'm trying to draw a choropleth map with this tool. I have my data in a database and I'm trying to show some of them in a map.
First, I launch my das application : app = dash.Dash()
Once I'm connected to the database, I execute the following code:
#Load dataframes
df = pd.read_sql('SELECT * FROM Companies_Public', con=db_connection)
#Choropleth map
app.layaout = html.Div([
dcc.Graph(
id = 'Map',
figure={
'data': [ dict(
type = 'choropleth',
locations = df['ISOCountry'],
z = sum(df['FinalPointsPerDemography']),
text = df['CountryName'],
colorscale = [[0,"rgb(5, 10, 172)"],[0.35,"rgb(40, 60, 190)"],[0.5,"rgb(70, 100, 245)"],\
[0.6,"rgb(90, 120, 245)"],[0.7,"rgb(106, 137, 247)"],[1,"rgb(220, 220, 220)"]],
autocolorscale = False,
reversescale = True,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5
) ),
colorbar = dict(
autotick = False,
tickprefix = '$',
title = 'Points<br>'),
) ],
'layout': go.Layout(
title = 'Points by Company per Demography',
geo = dict(
showframe = False,
showcoastlines = False,
projection = dict(
type = 'Mercator'
)
)
)
}
)
])
# Add the server clause:
if __name__ == '__main__':
app.run_server()
I get the next message in the console:
dash.exceptions.NoLayoutException: The layout was None at the time that run_server was called. Make sure to set the layout attribute of your application before running the server.
The following figure shows the structure of df:
df structure

Related

Changing choropleth symbology with drop down # plotly

Hi I am quite new to plotly and trying to create a choropleth covid map with different symbology with a button selector. problem I have is I can’t achieve different symbology.
Thanks in advance!
Here’s what I have so far:
df= pd.read_csv (covid.csv)
data=dict(type=‘choropleth’,
locations = df[‘Name’],
locationmode = ‘country names’,
z = df[‘Total’] # I believe here is my problem if I do z=[‘total’, ‘1M_pop’] I lost data
marker_line_color = ‘black’,
marker_line_width = 0.5,
)
layout=dict(title_text = ‘Cases today by country’,
title_x = 0.5,
geo=dict(
showframe = True,
showcoastlines = True,
projection_type = ‘mercator’
)
)
map=go.Figure( data=[data], layout =layout)
#buttons test
fig[“layout”]
fig[“layout”].pop(“updatemenus”)
fig.update_geos(fitbounds=“locations”, visible=True)
button1 = dict(method = “restyle”,
args = [{‘z’: [ df[“Total”] ] }, [“colorscale”, “Greens”]],
label = “Total Cases”)
button2 = dict(method = “restyle”,
args = [{‘z’: [ df[“1M_pop”] ]},[“colorscale”, “reds”]],
label = “Cases per 1M”)
fig.update_layout(width=1000,
coloraxis_colorbar_thickness=23,
updatemenus=[dict(y=1.1,
x=0.275,
xanchor=‘right’,
yanchor=‘bottom’,
active=0,
buttons=[button1, button2])
])
plot(fig, filename=‘covid.html’)```
[plotly][1]
[1]: https://i.stack.imgur.com/BV3gh.png
have plugged in OWID data to make it re-producable. Additionally you quotes and double-quotes were unusable so had to change to standard quote
I could get changes in z to work in updatemenus. Getting colorscale to work was not working
switched techniques, generate two similar traces then use updatemenus to control visibility
import requests, io
import pandas as pd
import plotly.graph_objects as go
# df= pd.read_csv (covid.csv)
df = pd.read_csv(
io.StringIO(
requests.get(
"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv"
).text
)
)
df = df.rename(
columns={
"location": "Name",
"total_cases": "Total",
"total_cases_per_million": "1M_pop",
}
)
data = dict(
type="choropleth",
locations=df["Name"],
colorscale="reds",
locationmode="country names",
z=df[
"Total"
], # I believe here is my problem if I do z=['total', '1M_pop'] I lost data
marker_line_color="black",
marker_line_width=0.5,
)
layout = dict(
title_text="Cases today by country",
title_x=0.5,
geo=dict(showframe=True, showcoastlines=True, projection_type="mercator"),
)
fig = go.Figure(
data=[
data,
{**data, **{"z": df["1M_pop"], "colorscale": "blues", "visible": False}},
],
layout=layout,
)
# buttons test
fig["layout"]
fig["layout"].pop("updatemenus")
fig.update_geos(fitbounds="locations", visible=True)
button1 = dict(
method="update",
args=[{"visible": [True, False]}],
label="Total Cases",
)
button2 = dict(
method="update",
args=[{"visible": [False, True]}],
label="Cases per 1M",
)
fig.update_layout(
width=1000,
coloraxis_colorbar_thickness=23,
updatemenus=[
dict(
y=1.1,
x=0.275,
xanchor="right",
yanchor="bottom",
active=0,
buttons=[button1, button2],
)
],
)
fig

Plotly interactive plot python: Change the dropdown menu to input box

I want to change the dropdown button with an input box so I can search for the item by starting to type the name and then select. So far I have a drop down box where you can select either one item or all of them at the same time. However, I want the user to be able to start typing the name of the item and then click and select the item they want to display their graph.
As I am new to plotly, any suggestion is very welcome and appreciated :)
Here is what the plot looks like so far:
My code:
def interactive_multi_plot(actual, forecast_1, forecast_2, title, addAll = True):
fig = go.Figure()
for column in forecast_1.columns.to_list():
fig.add_trace(
go.Scatter(
x = forecast_1.index,
y = forecast_1[column],
name = "Forecast_SI"
)
)
button_all = dict(label = 'All',
method = 'update',
args = [{'visible': forecast_1.columns.isin(forecast_1.columns),
'title': 'All',
'showlegend':True}])
for column in forecast_2.columns.to_list():
fig.add_trace(
go.Scatter(
x = forecast_2.index,
y = forecast_2[column],
name = "Forecast_LSTM"
)
)
button_all = dict(label = 'All',
method = 'update',
args = [{'visible': forecast_2.columns.isin(forecast_2.columns),
'title': 'All',
'showlegend':True}])
for column in actual.columns.to_list():
fig.add_trace(
go.Scatter(
x = actual.index,
y = actual[column],
name = "True values"
)
)
button_all = dict(label = 'All',
method = 'update',
args = [{'visible': actual.columns.isin(actual.columns),
'title': 'All',
'showlegend':True}])
fig.layout.plot_bgcolor = '#010028'
fig.layout.paper_bgcolor = '#010028'
def create_layout_button(column):
return dict(label = column,
method = 'update',
args = [{'visible': actual.columns.isin([column]),
'title': column,
'showlegend': True}])
fig.update_layout(
updatemenus=[go.layout.Updatemenu(
active = 0,
buttons = ([button_all] * addAll) + list(actual.columns.map(lambda column: create_layout_button(column)))
)
]
)
# Update remaining layout properties
fig.update_layout(
title_text=title,
height=800,
font = dict(color='#fff', size=12)
)
fig.show()
This is the error I receive:
small changes to interactive_multi_plot().
for all three add_trace() add meta = column for each of the scatter creations
change to return fig instead of fig.show()
simulate some data and call interactive_multi_plot(). I have assumed all three data frames have the same columns
S = 100
C = 10
actual = pd.DataFrame(
{
c: np.sort(np.random.uniform(0, 600, S))
for c in [
f"{a}{b}-{c}"
for a, b, c in zip(
np.random.randint(100, 200, C),
np.random.choice(list("ABCDEF"), C),
np.random.randint(300, 400, C),
)
]
}
)
f1 = actual.assign(**{c:actual[c]*1.1 for c in actual.columns})
f2 = actual.assign(**{c:actual[c]*1.2 for c in actual.columns})
fig = interactive_multi_plot(actual, f1, f2, "Orders")
solution
use dash this does support interactive drop downs
simple case of show figure and define a callback on item selected from dash drop down
it could be considered that updatemenus is now redundant. I have not considered sync of updatemenus back to dash drop down
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
# Build App
app = JupyterDash(__name__)
app.layout = html.Div(
[
dcc.Dropdown(
id="lines",
options=[{"label": c, "value": c} for c in ["All"] + actual.columns.tolist()],
value="All",
),
dcc.Graph(id="interactive-multiplot", figure=fig),
]
)
#app.callback(
Output("interactive-multiplot", "figure"),
Input("lines", "value"),
State("interactive-multiplot", "figure"),
)
def updateGraphCB(line, fig):
# filter traces...
fig = go.Figure(fig).update_traces(visible=False).update_traces(visible=True, selector={"meta":line} if line!="All" else {})
# syn button to dash drop down
fig = fig.update_layout(updatemenus=[{"active":0 if line=="All" else actual.columns.get_loc(line)+1}])
return fig
app.run_server(mode="inline")

Plotting data from two different dataframes to a single Dash graph

I'm trying to generate a Dash app which displays historical and forecasted housing prices. I've got the forecasted data stored in a different dataframe from the historical prices, and I'd like to plot them both on the same graph in Dash, and have the graph get updated via callback when the user picks a different city from a dropdown menu. I would like both traces of the graph to update when a value is selected in the dropdown. I've tried various things but can only get one trace from one dataframe plotted for the graph in my callback:
# --- import libraries ---
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Output, Input
# --- load data ---
df_h = pd.read_csv('df_h.csv')
df_arima = pd.read_csv('df_arima.csv')
options = [] #each column in the df_h dataframe is an option for the dropdown menu
for column in df_h.columns:
options.append({'label': '{}'.format(column, column), 'value': column})
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# --- initialize the app ---
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# --- layout the dashboard ---
app.layout = html.Div(
children = [
html.Div([
html.Label('Select a feature from drop-down to plot'),
dcc.Dropdown(
id = 'city-dropdown',
options = options,
value = 'Denver, CO',
multi = False,
clearable = True,
searchable = True,
placeholder = 'Choose a City...'),
html.Div(id = 'forecast-container',
style = {'padding': '50px'}),
]),
],
)
# --- dropdown callback ---
#app.callback(
Output('forecast-container', 'children'),
Input('city-dropdown', 'value'))
def forecast_graph(value):
dff = df_h[['Date', value]] #'value' is identical between the two dataframes. references
dfa = df_arima[df_arima['City'] == value] # a col in dff and row values in dfa
return [
dcc.Graph(
id = 'forecast-graph',
figure = px.line(
data_frame = dff,
x = 'Date',
y = value).update_layout(
showlegend = False,
template = 'xgridoff',
yaxis = {'title': 'Median Home Price ($USD)'},
xaxis = {'title': 'Year'},
title = {'text': 'Median Home Price vs. Year for {}'.format(value),
'font': {'size': 24}, 'x': 0.5, 'xanchor': 'center'}
),
)
]
I was able to accomplish this in Plotly but can't figure out how to do it in Dash. This is what I want in Dash:
Plotly graph I am trying to reproduce in callback, that is linked to a dropdown menu
This is all I can get to work in Dash:
Only one dataframe plots in Dash
This is the code that works in plotly graph objects:
from statsmodels.tsa.arima_model import ARIMA
df_ml = pd.read_csv('df_ml.csv')
# --- data cleaning ---
df_pred = df_ml[df_ml['RegionName'] == city]
df_pred = df_pred.transpose().reset_index().drop([0])
df_pred.columns = ['Date', 'MedianHomePrice_USD']
df_pred['MedianHomePrice_USD'] = df_pred['MedianHomePrice_USD'].astype('int')
df_pred['Date'] = pd.to_datetime(df_pred['Date'])
df_pred['Date'] = df_pred['Date'].dt.strftime('%Y-%m')
df_model = df_pred.set_index('Date')
model_data = df_model['MedianHomePrice_USD']
def house_price_forecast(model_data, forecast_steps, city):
#--- ARIMA Model (autoregressive integrated moving average) ---
model = ARIMA(model_data, order = (2,1,2), freq = 'MS')
res = model.fit()
forecast = res.forecast(forecast_steps)
forecast_mean = forecast[0]
forecast_se = forecast[1]
forecast_ci = forecast[2]
df_forecast = pd.DataFrame()
df_forecast['Mean'] = forecast_mean.T
df_forecast['Lower_ci'], df_forecast['Upper_ci'] = forecast_ci.T
df_forecast['Date'] = pd.date_range(start = '2021-02', periods = forecast_steps, freq = 'MS')
df_forecast['Date'] = df_forecast['Date'].dt.strftime('%Y-%m')
df_forecast.index = df_forecast['Date']
fig = go.Figure()
fig.add_trace(go.Scatter(x = df_pred['Date'], y = df_pred['MedianHomePrice_USD'],
mode = 'lines', name = 'Median Home Price ($USD)',
line_color = 'rgba(49, 131, 189, 0.75)', line_width = 2))
fig.add_trace(go.Scatter(x = df_forecast.index, y = df_forecast['Mean'],
mode = 'lines', line_color = '#e6550d',
name = 'Forecast mean'))
fig.add_trace(go.Scatter(x = df_forecast.index, y = df_forecast['Upper_ci'],
mode = 'lines', line_color = '#e0e0e0', fill = 'tonexty',
fillcolor = 'rgba(225,225,225, 0.3)',
name = 'Upper 95% confidence interval'))
fig.add_trace(go.Scatter(x = df_forecast.index, y = df_forecast['Lower_ci'],
mode = 'lines', line_color = '#e0e0e0', fill = 'tonexty',
fillcolor = 'rgba(225,225,225, 0.3)',
name = 'Lower 95% confidence interval'))
fig.update_layout(title = 'Median Home Price in {}, {} - {} (Predicted)'.format(
city, model_data.idxmin()[:-3], df_forecast_mean.idxmax()[:-3]),
xaxis_title = 'Year', yaxis_title = 'Median Home Price ($USD)',
template = 'xgridoff')
fig.show()
house_price_forecast(model_data, 24, 'Denver, CO') #24 month prediction
Perhaps a more succinct way of asking this question: How do I add a trace to an existing Dash graph, with data from a different dataframe, and both traces get updated when the user selects a value from a single dropdown?
Figured it out...
Don't use the syntax I used above in your callback. Put the px.line call inside a variable(fig, in this case), and then use fig.add_scatter to add data from a different dataframe to the graph. Both parts of the graph will update from the callback.
Also, fig.add_scatter doesn't have a dataframe argument, so use df.column or df[column] (ex. 'dfa.Date' below)
# --- import libraries ---
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px
from dash.dependencies import Output, Input
# --- load data ---
df_h = pd.read_csv('df_h.csv')
df_h['Date'] = pd.to_datetime(df_h['Date'])
df_arima = pd.read_csv('df_arima.csv')
df_arima['Date'] = pd.to_datetime(df_arima['Date'])
df_arima['Date'] = df_arima['Date'].dt.strftime('%Y-%m')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# --- initialize the app ---
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Graph(id = 'forecast-container')
]
)
# --- dropdown callback ---
#app.callback(
Output('forecast-container', 'figure'),
Input('city-dropdown', 'value'))
def update_figure(selected_city):
dff = df_h[['Date', selected_city]]
# dff[selected_city] = dff[selected_city].round(0)
dfa = df_arima[df_arima['City'] == selected_city]
fig = px.line(dff, x = 'Date', y = selected_city,
hover_data = {selected_city: ':$,f'})
fig.add_scatter(x = dfa.Date, y = dfa.Mean,
line_color = 'orange', name = 'Forecast Mean')
fig.add_scatter(x = dfa.Date, y = dfa.Lower_ci,
fill = 'tonexty', fillcolor = 'rgba(225,225,225, 0.3)',
marker = {'color': 'rgba(225,225,225, 0.9)'},
name = 'Lower 95% Confidence Interval')
fig.add_scatter(x = dfa.Date, y = dfa.Upper_ci,
fill = 'tonexty', fillcolor = 'rgba(225,225,225, 0.3)',
marker = {'color': 'rgba(225,225,225, 0.9)'},
name = 'Upper 95% Confidence Interval')
fig.update_layout(template = 'xgridoff',
yaxis = {'title': 'Median Home Price ($USD)'},
xaxis = {'title': 'Year'},
title = {'text': 'Median Home Price vs. Year for {}'.format(selected_city),
'font': {'size': 24}, 'x': 0.5, 'xanchor': 'center'})
return fig
if __name__ == '__main__':
app.run_server(debug = True)

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)
...

Python Plotly - Align Y Axis for Scatter and Bar

I'm trying to create a plotly graph with a Scatter and Graph elements. It all goes nicely, but one issue - the two Y axis don't align around 0.
I have tried playing with different attributes, such as 'mirror' and tick0, I also tried following the examples on plotly's site, but it's mostly multiple y-axis with the same graph type.
What can I do to fix this?
import utils
import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
pd_data ['dt'] = ... dates
pd_data['price'] = ... prices
pd_data['car'] = ... cars
price = go.Scatter(
x = pd_data['dt'],
y = pd_data['price'],
mode = 'lines',
name = 'Price',
xaxis = 'x',
yaxis='y1',
marker = dict(
color = utils.prep_color_string('orange'),
),
line = dict(
width = utils.line_width,
),
)
car = go.Bar(
x = pd_data['dt'],
y = pd_data['car'],
#mode = 'lines',
name = 'Cars',
xaxis = 'x',
yaxis='y2',
marker = dict(
color = utils.prep_color_string('light_green'),
),
#line = dict(
# width = utils.line_width,
#),
)
data = [price, car]
layout = dict(
title = 'Price/Car',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
),
yaxis=dict(
title = 'Price',
tickprefix = "$",
overlaying='y2',
anchor = 'x'
),
yaxis2=dict(
title = 'Car',
dtick = 1,
#tickprefix = "",
side = 'right',
anchor = 'x',
),
)
fig = dict( data=data, layout=layout)
div = plotly.offline.plot( fig, validate=False, output_type = 'file',filename='graph.html' ,auto_open = False)
I have been struggling with this as well. Exact same problem, but I am using R. The way I figured around it was to use the rangemode="tozero" for both the yaxis and yaxis2 layouts.
I think in your case, it would look like this:
layout = dict(
title = 'Price/Car',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
),
yaxis=dict(
title = 'Price',
tickprefix = "$",
overlaying='y2',
anchor = 'x',
rangemode='tozero'
),
yaxis2=dict(
title = 'Car',
dtick = 1,
#tickprefix = "",
side = 'right',
anchor = 'x',
rangemode = 'tozero'
),
)
Let me know if that works for you.

Categories