Plotly: Blank choropleth map after exporting to HTML - python

I'm trying to build an interactive, simple choropleth heatmap of all the countries in Asia. The plot displays well when in my Jupyter Notebook, but when I try to export it to html, it shows only blank.
The GeoJSON file that I'm using is this one, it's the first result when I google "asia geojson"
A preview of my DataFrame file can be seen here.
My code:
import pandas
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
import plotly
fig = px.choropleth(df, geojson=asia, locations='country', color='population', color_continuous_scale="reds", scope = 'asia', featureidkey="properties.admin", labels={'population':'Population Count'}, center={"lat": 30, "lon": 100})
fig.show()
plotly.offline.plot(fig, filename='myplot.html')
[Screenshot] How it looks on my Jupyter Notebook
[Screenshot] How it looks on my web browser
As we can see, the .html file shows nothing when opened in my web browser. I've read the documentations and the majority of users having similar problems, yet I can't seem to make mine work.
I tried to plot the sample dataset of USA Census Data from their official guide and it exports normally into .html, as expected.
How can I fix this? Any help would be appreciated :)

Here is an example code to output to html format. The geojson file you are using is associated with the data used on the official plotly website, and saved in an html file. My environment is jupyterLab 2.2.0 to check the file saving.
Data for some countries is not shown, but if you replace it with your own data, it should be fine.
from urllib.request import urlopen
import json
with urlopen('https://gist.githubusercontent.com/hrbrmstr/94bdd47705d05a50f9cf/raw/0ccc6b926e1aa64448e239ac024f04e518d63954/asia.geojson') as response:
asia = json.load(response)
import plotly.express as px
df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, geojson=asia,
locations='iso_alpha',
color='pop',
color_continuous_scale="reds",
scope = 'asia',
featureidkey="properties.sov_a3",
labels={'population':'Population Count'},
center={"lat": 30, "lon": 100})
fig.show()
fig.write_html("myplot.html")

EDIT: Try this.
I have imported plotly offline as pyo and ran your fig via pyo.plot() which outputs an html file to the dir of your notebook.
from urllib.request import urlopen
import json
with urlopen('https://gist.githubusercontent.com/hrbrmstr/94bdd47705d05a50f9cf/raw/0ccc6b926e1aa64448e239ac024f04e518d63954/asia.geojson') as response:
asia = json.load(response)
import plotly.express as px
import plotly.offline as pyo
df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, geojson=asia,
locations='iso_alpha',
color='pop',
color_continuous_scale="reds",
scope = 'asia',
featureidkey="properties.sov_a3",
labels={'population':'Population Count'},
center={"lat": 30, "lon": 100})
fig.show()
pyo.plot(fig)

Related

The graph is not showing up in my jupyter notebook in kaggle

I am not able to see my plot in my kaggle notebook.
The following is my code.
import ipywidgets as widgets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
import seaborn as sns
df = pd.read_csv('../input/sdd1247/COMED_hourly.csv', parse_dates=["Datetime"], index_col="Datetime")
def Visualization_plots(x):
y = df.loc['2017']
y['COMED_MW'].resample('H').mean().plot()
button = widgets.Button(
description='Submit',
disabled=False,
button_style='success', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon='alicorn' # (FontAwesome names without the `fa-` prefix)
)
button.on_click(Visualization_plots)
button
The button shows up.. but when I click on it, I expected the graph to show below it. But nothing shows up.
I do however see the graph in the console. How can I show the graph in my notebook instead?
This is how it shows up in the console window:
I would add plt.show() on the line after the plot instruction.
If it doesn't work please provide a few lines of your dataset.

Plotly Chart-Studio config question to change Modebar in Python

I've created a simple Plotly chart in Python, and I can change the Modebar options quite easily. However, when I'm trying to publish the same chart to Chart-Studio, not all the Modebar configurations are working. Any ideas?
Here is the code:
import pandas as pd
import numpy as np
import plotly.graph_objects as go
df = pd.DataFrame({'a':[2,4,6,8,10],'b':[3,6,9,12,15]})
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df['a'], mode='lines', name='a', line=dict(color='dodgerblue', dash='solid')))
fig.add_trace(go.Scatter(x=df.index, y=df['b'], mode='lines', name='b', line=dict(color='lightsalmon', dash='dash')))
fig.update_layout(
title='a and b',
autosize=False,
width=500,
height=500,
newshape=dict(line_color='mediumaquamarine', line_width=2, opacity=1)
)
config = {
'modeBarButtonsToAdd' : ['drawline', 'drawopenpath', 'drawrect', 'eraseshape'],
'displaylogo' : False
}
fig.show(config=config)
The figure that appears has the logo removed and the additional buttons on the modebar showing as it should...
However, if I try to publish this to Chart-Studio:
import chart_studio.plotly as py
import chart_studio
chart_studio.tools.set_credentials_file(username='xxxxx', api_key='#####')
py.plot(fig, filename='a and b', auto_open=False, config=config)
This doesn't work. Note, the logo doesn't appear so I thought that part was working, but actually if I turn displaylogo=True then it doesn't show the logo either. So it appears none of the config arguments are working.
I'm not sure if this is exactly the way to update config in Chart-Studio but I can't find any documentation for it, I tried this based on this old post:
Adding config modes to Plotly.Py offline - modebar
I also tried saving the fig file with the config argument and publishing that but that gives an error. What I've tried here doesn't give an error but it doesn't do anything.
Thanks

Map with Choroplethmapbox isn't showing in Dash

I am trying to build a map with Choroplethmapbox in Dash, but I cannot plot in that.
I test the geojson with another tool and in that tools, the map is drawn correctly, but not with Choroplethmapbox.
Any idea about what I am doing wrong?
Thanks
GeoJson:
https://gist.github.com/Tlaloc-Es/5c82834e5e4a9019a91123cb11f598c0
Python Dash Code:
import json
with open('mexico.geojson') as f:
counties = json.load(f)
fig = go.Figure(go.Choroplethmapbox(
geojson=counties,
locations=df['COV_'],
z=df['Enero'],
colorscale="Viridis", zmin=0, zmax=df['Enero'].max(),
marker_opacity=0.5, marker_line_width=0))
fig.update_layout(mapbox_style="carto-positron",
mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129})
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
looks like you are missing the fig.show() at the bottom and import plotly.graph_objects as go at the top. The code below will open a map, but data is needed for the choropleth values. You have df in your code example but you did not include a csv. If you want to us the df that is in your code, import pandas, and create a data frame called df from the csv. Here is a link that can help with that. Pandas dataframes
import json
import plotly.graph_objects as go
with open(r'{insert file path here}.geojson') as f:
counties = json.load(f)
fig = go.Figure(go.Choroplethmapbox(
geojson=counties,
colorscale="Viridis", zmin=0, zmax=100,
marker_opacity=0.5, marker_line_width=0))
fig.update_layout(mapbox_style="carto-positron",
mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129})
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
Here is an example of using pandas with you json.Further explanation of the code below can be found here
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
I needed to add an id filed wit this code:
I used the code of this page: https://community.plot.ly/t/plot-a-shapefile-shp-in-a-choropleth-chart/27850
I had to solve a similar problem and this is my solution applied to your problem (although with px.choropleth_mapbox instead of graph_objects which I found confusing for choropleths).
The data that you link does not (at least not at the time of writing) have the column 'Enero'.
You never define a Dash-app (app.layout = ...), while you can probably serve without it and just have fig.show() as suggested, explicit beats implicit. Thus creating a layout section is better.
If I understand how it works, if you use GeoPandas you do not have to generate an 'id' or anything like that as you suggest in your own answer.
Anyways, hopefully my solution can serve as a working start for you. I added radio buttons so that you can select what data column to use for color.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.express as px
import geopandas as gpd
print('Loading data...')
gdf = gpd.read_file('https://gist.githubusercontent.com/Tlaloc-Es/5c82834e5e4a9019a91123cb11f598c0/raw/709ce9126861ef7a7c7cc4afd6216a6750d4bbe1/mexico.geojson')
gdf = gdf.to_crs(epsg=4326)
print('Done!')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div([
dcc.RadioItems(
id='radio-color_on',
options=[{'label': i, 'value': i} for i in ['AREA','PERIMETER']],
value='AREA',
labelStyle={'display': 'inline-block'}
),
],style={'width': '40%', 'display': 'inline-block',}),
html.Div([], style={'width':'100%'}),
html.Div([
dcc.Graph(id="fig")
],style={'width': '100%', 'display': 'inline-block', 'padding': '0 10',},),
])
#app.callback(
Output("fig", "figure"),
[Input("radio-color_on", "value")])
def draw_choropleth(color_on):
fig = px.choropleth_mapbox(gdf,
geojson=gdf.geometry,
locations=gdf.index,
color=color_on,
color_continuous_scale="Viridis",
#range_color=(0, 12),
mapbox_style="carto-positron",
zoom=4,
center = {"lat":gdf.centroid.y.mean(), "lon":gdf.centroid.x.mean()},
opacity=0.5,
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
height=700,
)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
Saving this code to a file "myapp.py" and running it in the terminal as python myapp.py starts the development served, firing up a web browser, navigating to the url that it uses (it writes it out in the terminal, usually 172.0.0.1:8050) gives you this:
I am running these versions, from the defaults anaconda channel.
dash 1.19.0
dash-core-components 1.3.1
dash-html-components 1.0.1
dash-renderer 1.1.2
flask 1.1.2
geopandas 0.8.1
PS. I actually used the data to ask a question about dash choropleth mapbox selection behavior (Selection behavior in plotly-dash Choropleth mapbox plot). Thanks!
I have similar problems. With the show method, it works fine, sometimes with the dash too (using only callbacks). The problem occurs due to the really old version of dash, installed via default channel of anaconda (only one version 1.4.1). After installation via conda-forge channel newer version (in my case 1.13.4) it works.
conda install -c conda-forge dash dash-core-components \
dash-html-components dash-renderer dash-table

Showing plotly on jupyter notebook

I have a dataframe 'country' that I am plotting using jupyter notebook.
It plotted nicely on Kaggle's notebook, but refuses to show when I use jupyter notebook..
I've read similar problems on StackOverflow, and I've tried both :
init_notebook_mode(connected=True)
&
py.offline.init_notebook_mode(connected=True)
Please find the full code below:
import plotly.offline as py
from plotly.offline import iplot
py.offline.init_notebook_mode(connected=True)
import plotly.graph_objs as go
trace1 = go.Bar(
x= country.index,
y= country['Avg. Points'],
name='Avg. Points'
)
trace2= go.Bar(
x= country.index,
y= country['Avg. Price'],
name='Avg. Price'
)
data=[trace1, trace2]
layout=go.Layout(
barmode='stack')
fig=go.Figure(data=data, layout=layout)
py.iplot(fig, filename='stacked-bar')
The below image is how it looks on Kaggle.
I tried using your code, replacing your data with some of Plotly's example data. I'm not able to replicate the issue you're having. Assuming you have correctly installed plotly using $ pip install plotly and there are no issues with the data, the following should work.
from plotly.offline import iplot isn't necessary, since you use py.iplot.
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=True)
trace1 = go.Bar(
x= country.index,
y= country['Avg. Points'],
name='Avg. Points'
)
trace2= go.Bar(
x= country.index,
y= country['Avg. Price'],
name='Avg. Price'
)
data=[trace1, trace2]
layout=go.Layout(barmode='stack')
fig=go.Figure(data=data, layout=layout)
py.iplot(fig, filename='stacked-bar')

Plotting Candle Stick in Python

I am trying to plot a candle stick chart in python. Here is my code
from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')
This is the error I am getting
PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'.
Any idea how I can draw a Candle Stick Chart?
The problem must be because you didn't provide the username and api key which you will get from the https://plot.ly/settings/api link. If you want to use plotly online to create this graph. First create an account, then get the username and api key and insert it in the below code.
from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py.sign_in('<<username here>>', '<<api key here>>')
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')
There is another option of using plotly offline which does not need all this procedure, please find below the implementation code.
from pandas_datareader import data as pdr
import plotly.offline as py_offline
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py_offline.init_notebook_mode()
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py_offline.iplot(data, filename='Candle Stick')
#for Spyder plotting use the below line instead
#py_offline.plot(data, filename='Candle Stick')
Please make sure to install the libraries pandas_datareader and fix_yahoo_finance using pip, if these libraries are not already present!

Categories