I am working on choropleth using plotly in Jupyter Notebook.I want to plot choropleth but its showing me empty output.I am working with offline plotly.In html its genrated chart successfuly but when i tried offline it shows me empty output.please tell me how i solve this error.
here is my code
from plotly.graph_objs import *
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.offline.offline import _plot_html
init_notebook_mode(connected=True)
for col in state_df.columns:
state_df[col] = state_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)']]
state_df['text'] = state_df['StateCode'] + '<br>' +'TotalPlans '+state_df['TotalPlans']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = state_df['StateCode'],
z = state_df['TotalPlans'].astype(float),
locationmode = 'USA-states',
text = state_df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)
),
colorbar = dict(
title = "Millions USD"
)
) ]
layout = dict(
title = 'Plan by States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
plotly.offline.iplot(fig)
You are passing a dictionary to iplot which in contradiction to the documentation can handle only Figure objects and not dictionaries.
Try
fig = Figure(data=[data], layout=layout)
and it should work.
Related
I need to plot a 1 km by 1 km grid on mapbox map in plolty.I am attaching a code, but I am stuck in adding a grid and also integrating mapbox token.
Below is the code to the map I have made.
shp_path = "Path to shape file"
sf = shp.Reader(shp_path)
def read_shapefile(sf):
fields = [x[0] for x in sf.fields][1:]
records = sf.records()
shps = [s.points for s in sf.shapes()]
df = pd.DataFrame(columns=fields, data=records)
df = df.assign(coords=shps)
return df
fig = px.scatter_mapbox(df, lat="LAT", lon="LONG",
size_max=30, zoom=12.5,
height = 600, width = 1000, #center = dict(lat = g.center)
title='Drive Route with Mapbox',
#mapbox_style="open-street-map"
)
fig.update_layout(font_size=16, title={'xanchor': 'center','yanchor': 'top', 'y':0.9, 'x':0.5,},
title_font_size = 24, mapbox_accesstoken=api_token, mapbox_style = "mapbox://styles/strym/ckhd00st61aum19noz9h8y8kw")
fig.update_traces(marker=dict(size=6))
We tried integrating the mapbox token into the code, but it keeps giving an error:
mapbox_token = requests.get('https://api.mapbox.com/?access_token=gridactivity').text
px.set_mapbox_access_token(mapbox_token)
fig = ff.create_hexbin_mapbox(
data_frame=df, lat="centroid_lat", lon="centroid_lon",
nx_hexagon=10, opacity=0.9, labels={"color": "Point Count"},
)
fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))
fig.show()
This shows an empty map
I'm trying to plot the intensity of CO2 emissions per country using plotly ,
Most of the countries don't even exceed 10k, but the color range is from 0 to 35k , how do I change that?
Here's my code:
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>'''))
init_notebook_mode(connected=False)
data = dict(type = 'choropleth',
locations = fmmcgrf['Entity'],
locationmode = 'country names',
z = fmmcgrf['CO2'],
text = fmmcgrf['Entity'],
colorbar = {'title':'CO2'})
layout = dict(title = 'Co2',
geo = dict(showframe = False,
projection = {'type': 'winkel tripel'}))
map = go.Figure(data = [data], layout=layout)
enable_plotly_in_cell()
map.show()
I customized the color bar with the example from the official reference.
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = 'Blues',
autocolorscale=False,
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '$',
colorbar_tickvals=[0,10000,15000],# update
colorbar_title = 'GDP<br>Billions US$',
))
fig.update_layout(
title_text='2014 Global GDP',
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
)
fig.show()
I have a dataframe tx_user_type_revenue:
I create a plot using plotly but for some reason it shows me an extra line. This code works fine for other data.
import plotly.plotly as py
import plotly.offline as pyoff
import plotly.graph_objs as go
#filtering the dates and plot the result
tx_user_type_revenue = tx_user_type_revenue.query("InvoiceYearMonth > 201601 and InvoiceYearMonth < 201901")
plot_data = [
go.Scatter(
x=tx_user_type_revenue.query("UserType == 'Existing'")['InvoiceYearMonth'],
y=tx_user_type_revenue.query("UserType == 'Existing'")['Revenue'],
name = 'Existing'
),
go.Scatter(
x=tx_user_type_revenue.query("UserType == 'New'")['InvoiceYearMonth'],
y=tx_user_type_revenue.query("UserType == 'New'")['Revenue'],
name = 'New'
)
]
plot_layout = go.Layout(
xaxis={"type": "category"},
title='New vs Existing Customers Revenue'
)
fig = go.Figure(data=plot_data, layout=plot_layout)
pyoff.iplot(fig)
I am trying to plot geojson geometries with plotly using scattermapbox.
This piece of code converts data successfully from geopandas for plotly to work with:
from plotly.offline import download_plotlyjs, init_notebook_mode,
plot, iplot
import plotly.graph_objs as go
mapbox_access_token = 'mykey'
import json
from_json = geopandas_gdf.to_json()
geoJSON = json.loads(from_json)
pts=[]#list of points defining boundaries of polygons
for feature in geoJSON['features']:
if feature['geometry']['type']=='Polygon':
pts.extend(feature['geometry']['coordinates'][0])
pts.append([None, None])#mark the end of a polygon
elif feature['geometry']['type']=='MultiPolygon':
for polyg in feature['geometry']['coordinates']:
pts.extend(polyg[0])
pts.append([None, None])#end of polygon
else: raise ValueError("geometry type irrelevant for map")
X, Y=zip(*pts)
I am able to plot this data on blanc figure with the following code:
axis_style=dict(showline=False,
mirror=False,
showgrid=False,
zeroline=False,
ticks='',
showticklabels=False)
layout=dict(title='map',
width=700, height=700,
autosize=False,
xaxis=axis_style,
yaxis=axis_style,
hovermode='closest')
fig=dict(data=data, layout=layout)
plot(fig, filename='map')
But I can not plot this on scattermapbox. Trying like this:
data = [
go.Scattermapbox(
lat=X,
lon=Y,
line = go.scattermapbox.Line(width=5,
color='red'))
]
layout = go.Layout(
autosize=True,
hovermode='closest',
mapbox=go.layout.Mapbox(
accesstoken=mapbox_access_token,
bearing=0,
center=go.layout.mapbox.Center(
lat=53,
lon=0
),
pitch=0,
zoom=5
),
)
fig = go.Figure(data=data, layout=layout)
plot(fig, filename='Montreal Mapbox')
thank you!
I have managed to do this with the following:
layout = go.Layout(
height=1500,
autosize=True,
hovermode='closest',
mapbox=dict(
layers=[
dict(
sourcetype = 'geojson',
source = geoJSON,
type = 'fill',
color = 'rgba(163,22,19,0.8)'
)
],
accesstoken=mapbox_access_token,
bearing=0,
center=dict(
lat=53,
lon=0
),
pitch=0,
zoom=5.2,
style='light'
),
)
But then the other question arises: how to provide data from json to hover?
Answer to your secondary question
Provide Data from JSON to hover by using customdata attribute inside data that is passed to the plot.
Additionally: Could you please route a general json dataset, so that others can easily run your code blocks please?
Link to customdata attribute: https://plot.ly/python/reference/#scatter-customdata
Else, you could use text and mode='markers + text' to display data from text attribute on hover.
Trying to make a choropleth map in plotly using some data I have in a csv file. Have created the following map:
my choromap
This isn't a correct display of the data however. Here is an excerpt of my csv file:
China,2447
...
Trinidad And Tobago,2
Turkey,26
Ukraine,8
United Arab Emirates,97
United States of America,2008
Based on this I'd expected China to appear in a similar colour to that which the US has loaded in, however it looks the same as countries with values of less than 200. Does anyone know what the reason for this is?
Here's my full code for reference:
import pandas as pd
import plotly as py
df = pd.read_csv('app_country_data_minus_uk.csv')
data = [dict(type='choropleth',
locations = df['Country'],
locationmode = 'country names',
z = df['Applications'],
text = df['Country'],
colorbar = {'title':'Apps per country'},
colorscale = 'Jet',
reversescale = False
)]
layout = dict(title='Application Jan-June 2018',
geo = dict(showframe=False,projection={'type':'mercator'}))
choromap = dict(data = data,layout = layout)
red = py.offline.plot(choromap,filename='world.html')
per your comment I would make sure that china is indeed 2447 and not something like 244. I would also follow the plotly documentation although you example code works.
import plotly.plotly as py
import pandas as pd
df = pd.read_csv('app_country_data_minus_uk.csv')
data = [ dict(
type = 'choropleth',
locations = df['Country'],
locationmode = 'country names',
z = df['Applications'],
colorscale = 'Jet',
reversescale = False,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5
) ),
colorbar = dict(
autotick = False,
tickprefix = '',
title = 'Apps per country'),
) ]
layout = dict(
title = 'app_country_data_minus_uk',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
)
)
fig = dict( data=data, layout=layout )
py.iplot( fig, validate=False, filename='d3-world-map' )
or if you want to plot it offline:
import plotly.plotly as py
import pandas as pd
import plotly
df = pd.read_csv('app_country_data_minus_uk.csv')
data = [ dict(
type = 'choropleth',
locations = df['Country'],
locationmode = 'country names',
z = df['Applications'],
colorscale = 'Jet',
reversescale = False,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5
) ),
colorbar = dict(
title = 'Apps per country'),
) ]
layout = dict(
title = 'app_country_data_minus_uk',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
)
)
fig = dict( data=data, layout=layout )
plotly.offline.plot(fig,filename='world.html')
If you use iplot you will be able to edit the chart and see the data in plotly to make sure your data looks correct