I am trying to plot a USA map using plotly package. Code is getting executed but nothing is getting displayed on the screen.
import plotly.graph_objs as go
import pandas as pd
data = dict(type = 'choropleth',locations = ['AZ','CA','NY'],locationmode='USA-states',colorscale='Portland',text=['text1','text2','text3']
,z=[1,0,2.0,3.0],colorbar={'title' : 'USA States Data'})
layout = dict(geo={'scope' : 'usa'})
fig = go.Figure(data=[data],layout=layout)
fig.show()
Why nothing is getting displayed and no error is also raised?
Ran your code, it's working fine for me.
(Also, try and make your title more descriptive of the problem so that if someone faces a similar problem, they can easily find your question.)
Related
I have been able to successfully create a custom shapefile Choropleth map using plotly and geopandas. It loads successfully in my Jupyter window. The following image is what the map looks like when running in Jupyter.
Successfully rendered map in Jupyter
This is the code used to render the above map:
data = go.Choroplethmapbox(
geojson = gdf_json,
locations = df.index.astype(str),
z = df['2016']['Total'],
text = df.index.astype(str),
colorbar=dict(thickness=20,ticklen=3,tickformat=',.2r',outlinewidth=0),
marker_line_width=0.5,
marker_opacity=0.4,
colorscale='gnbu',
zmin=zmin,
zmax=zmax,
hovertemplate = "<b>%{text}</b><br>" +
"%{z:,.4r}<br>" +
"<extra></extra>")
#mapbox geographic map layout
layout = go.Layout(
title='Expenditure, 2020',
autosize=True,
#hovermode='closest',
#showlegend=True,
height=600,
margin=dict(l=0, r=0, t=40, b=0),
mapbox = dict(
domain = {'x': [0, 1],'y': [0, 1]},
center = dict(lat=-27.628296146695863, lon=152.74025612708698),
accesstoken = MAPBOX_ACCESSTOKEN,
#pitch=0,
zoom=10,
style='light')
)
fig = go.Figure(data=data, layout=layout)
fig.show()
However, when I attempt to load the map into Dash, it returns as an empty graph. (Note I cancel out the fig.show() line of code during this process).
app.layout = html.Div([
dcc.Graph(id = 'plot', figure = fig)
])
if __name__ == '__main__':
app.run_server()
Unsuccessful map in Dash
What I have tried
To narrow down the potential problems, I have tried to load in other elements such as dropdowns, radio buttons and a range slider. These loaded successfully, just not the map itself. I am also using the correct public Mapbox API token, as I have previously loaded up a Scattermapbox graph (created a bubble map), which has been successful on Dash.
Possible reasons
Obviously the starting point is whether there might be a very small minor syntax error in my code.
However I'm also wondering if there's something wrong with the loading of the geojson? Even though it loads successfully in Jupyter, maybe there is a slightly different method used when loading it into Dash?
To convert my geopandas polygons into geojson:
I converted it into an appropriate CRS --> gdf.to_crs(epsg=4326)
Set the index to my unique id --> gdf.set_index(id)
Applied this function --> gdf_json = gdf.__geo_interface__
Example of the geojson file
Would love some help if possible. Thank you!
I'm working on a very similar problem and when I converted from jupyter to dash I do not recall having to change the process of the geojson. But don't reject that possibility yet. The fact that it isn't producing any errors from the geojson is likely indicative of an error in how you build your layout. So the first two things you should try first.
Run the debugger (if you aren't already) because this will pick up on errors that will not be ported to your terminal.
app.run_server(debug=True)
Put your map rendering code into a function
def build_map():
return fig #after building the map figure
app.layout = html.Div[(dcc.Graph(figure = build_map())]
I ran into one error with building larger maps where it would time out.
There are so many things that could go wrong here, so process of elimination is key. Feel free to comment below and I will continue to try and help you out!
I am generating histograms using go.Histogram as described here. I am getting what is expected:
What I want to do is to show some statistics of the selected data, as shown in the next image (the white box I added manually in Paint):
I have tried this and within the function selection_fn I placed the add_annotation described here. However, it does nothing. No errors too.
How can I do this?
Edit: I am using this code taken from this link
import plotly.graph_objects as go
import numpy as np
x = np.random.randn(500)
fig = go.Figure(data=[go.Histogram(x=x)])
fig.show()
with obviously another data set.
I'm working on taking some data from a dataset and plotting certain aspects of it. Here's my code below:
import matplotlib.pyplot as plt
df1 = pd.read_csv('dataset_1.csv')
soil_moisture = list(df1.Soil_Moisture)
soil_temperature = list(df1.Soil_Temp)
print(len(soil_moisture))
print(len(soil_temperature))
plt.plot([soil_moisture], [soil_temperature])
plt.show()
As you can see, it takes data from each of those columns and tries to make a line graph. However, when I run, it just displays an empty graph. This is weird since when I print the soil_moisture and soil_temperature, it tells me that there's actual data, and none of my other plots in the same notebook are experiencing this. All help is appreciated!
Here's an image of the jupyter output
Please revise line 7 of your code as:
plt.plot(soil_moisture, soil_temperature)
When you use [soil_moisture] that means you are generating another list with list soil_moisture as its first element.
I have a problem about not showing show Mapbox in Jupyter.
I check if it works via https://api.mapbox.com/?access_token=myaccesstoken it always returns {"api":"mapbox"}
I updated token many times but nothing changed. How can I fix it?
Here is my code snippet.
import plotly.graph_objects as go
import plotly.io as pio
import plotly.express as px
access_token = 'my-mapbox-token'
px.set_mapbox_access_token(access_token)
fig = px.density_mapbox(...)
fig.update_layout(margin={"r":0,"t":30,"l":0,"b":0})
fig.show()
Can you try to pass the token with your first update_layout() call, in which you should set your map style:
fig.update_layout(mapbox_style="dark", mapbox_accesstoken=token)
See this example for reference:
https://plotly.com/python/mapbox-layers/
-> Go to example "Dark tiles from Mapbox service.."
I am running the following code to plot points against a city backdrop using Mapbox within Plotly in a Jupyter Notebook, but the plot does not show up, I just get a blue background.
I suspect that I am not using the token correctly?
import plotly.express as px
MBToken = 'pk.[mypublickey]'
px.set_mapbox_access_token(MBToken)
fig = px.scatter_mapbox(dfMaster.dropna()
, lat="latitude"
, lon="longitude"
, color="nta"
, size="count_of_testers"
#, color_continuous_scale=px.colors.cyclical.IceFire
#, size_max=15
#, zoom=10
)
fig.show()
#fig = px.scatter(x='latitude',y='longitude',data_frame=df)
#fig.show()
Running that gives me:
It does not appear to be a Plotly issue, the commented out code creates a scatter plot (although that has the same blue background, but the points show)
Some other posts have pointed to Jupyter offline mode being the possible culprit, but adding this did not resolve
import plotly.offline as pyo
pyo.init_notebook_mode()
Additionally, tried starting up the Jupyter notebook with a higher data rate limit as suggested, but no luck there either
This ended up being a silent data integrity error, as the size field was a string and needed to be converted into numeric