Plotly maps not showing in Jupyter Notebook in VS Code - python

stacks!
I'm trying to plot a graph using plotly, in Python. Specifically:
Plot: Maps, Bubblemaps, Choropleth..
Python: 3.9.6
Plotly: 4.01
Jupyter Notebook: 7.26
Env Manager: miniconda3
IDE: Ms. Visual Studio Code
I tried to run a code like this:
import plotly
import plotly.offline as pyo
pyo.init_notebook_mode()
import plotly.graph_objs as go
import plotly.express as ex
df = ex.data.gapminder().query("year==2007")
fig = ex.choropleth(df, locations="iso_alpha",
color="lifeExp", # lifeExp is a column of gapminder
hover_name="country", # column to add to hover information
color_continuous_scale=ex.colors.sequential.Plasma)
which is not my project code, just the example code of Plotly Map that I found on Plotly website (https://plotly.com/python/choropleth-maps/), but it's not showing anything.
P.S: I've tried to install plotly Jupyterlab dependencies from conda, i've also tried to use offline plotly but still nothing comes up. (Only the plot canvas and legend, the map is missing). Although, when I tried to make a bar chart it works. Help me masters!!!!!

Related

How to display plotly as svg in GitHub and interactive plotly while in local?

My goal is to display plotly charts in GitHub (interactive or not). The reason that I switch to Plotly instead of using matplotlib.pyplot or pandas.Series.plot is that it offers you interactive charts.
However, after pushing the .ipynb file to GitHub. I noticed that the charts are not showing up.
What I've tried:
# fix plotly is not showing in github.
# if you want to have interactive plotly, use `fig.show("notebook_connected")`
import plotly.io as pio
pio.renderers.default = "svg"
The problem is that the charts become not interactive even in local.
Changing it to pio.renderers.default = "svg+notebook", the charts will be interactive in local. But it won't show in GitHub.

How to save plotly offline figure inside jupyter notebook?

I am using plotly to plot figure inside jupyter notebook. After re-opening jupyter notebook, all the figures are not shown. I am wondering if it is possible to save the figures inside the notebook after being saved, just like using matplotlib or seaborn. Thanks
import plotly.graph_objects as go
import plotly
from plotly.offline import init_notebook_mode, iplot
from plotly.subplots import make_subplots
#fig=make_subplots(specs=[[{"secondary_y": True}]])
fig=go.Figure()
fig.add_scatter(x=differenced_data.index[-1*n_steps:], y=test.values,name='test data',mode='lines+markers',marker=dict(color='green',size=5)) #mode='markers','lines','lines+markers'
iplot(fig)

Plotly not showing graphs in pycharm

Iplot is not showing any output in pycharm and neither does it give any errorHere is the code I wrote

Save Jupyter Notebook with Plotly Express widgets displaying

I have a Jupyter notebook (python) where I used plotly express to plot in the notebook for analysis purposes.
I want to share this notebook with non-coders, and have the interactive visuals be available still - but it does not seem to work.
I tried following recommendations made here but even after saving widgets state and using nbconvert, when I open the new HTML file, the visuals are not available.
A sample line of plotting can be seen below:
import plotly_express as px
fig = px.scatter(
df,
x='size',
y='size_y',
color='clients',
hover_data=['id'],
marginal_y="histogram",
marginal_x="histogram"
)
fig.show()
After running plotly.offline.init_notebook_mode() in a cell,
you can export the notebook with full interactivity via the file menu:
File --> Export Notebook as... --> Export Notebook to HTML.
I was having similar issues but with JupyterLab. Followed the instructions here: https://plot.ly/python/renderers/ .
import plotly.io as pio
pio.renderers.keys()
I had to add the following snippet to my script:
import plotly.io as pio
pio.renderers.default = 'jupyterlab'
Exporting as HTML after that worked for me. You can read "Overriding the default renderer".
I suppose you would need
pio.renderers.default = 'notebook'
You can specify the default renderers from plotly with:
import plotly.io as pio
pio.renderers.default = 'pdf'
or when displaying the images with:
fig.show(renderer="pdf")
The 2 choices for you are:
'notebook': work well with jupyter notebook;
'pdf': perfect when using nbconvert to convert to HTML or LATEX
You can also join the 2 with "notebook+pdf" so you have iterative plots when running the notebook and static images when converting with nbconvert.
I just had a problem that resulted in this error message.
nbconvert/filters/widgetsdatatypefilter.py:69: UserWarning: Your element with mimetype(s) dict_keys(['application/vnd.plotly.v1+json']) is not able to be represented.
warn("Your element with mimetype(s) {mimetypes}"
Google brought me here, but I could not find a solution from the answers above.
I'm sharing the setup which caused my problem and the solution.
I was running the notebook in VS Code and then on the command line using: jupyter nbconvert
To solve it, I had to start jupyter lab and then run it and save it before running nbconvert.

plotly.offline.iplot gives a large blank field as its output in Jupyter Notebook/Lab

I am trying to create a Sankey chart in a Jupyter notebook, basing my code on the first example shown here.
I ended up with this, which I can run without getting any errors:
import numpy as npy
import pandas as pd
import plotly as ply
ply.offline.init_notebook_mode(connected=True)
df = pd.read_csv('C:\\Users\\a245401\\Desktop\\Test.csv',sep=';')
print(df.head())
print(ply.__version__)
data_trace = dict(
type='sankey',
domain = dict(
x = [0,1],
y = [0,1]
),
orientation = "h",
valueformat = ".0f",
node = dict(
pad = 10,
thickness = 30,
line = dict(
color = "black",
width = 0.5
),
label = df['Node, Label'].dropna(axis=0, how='any'),
color = df['Color']
),
link = dict(
source = df['Source'].dropna(axis=0, how='any'),
target = df['Target'].dropna(axis=0, how='any'),
value = df['Value'].dropna(axis=0, how='any'),
)
)
print(data_trace)
layout = dict(
title = "Test",
height = 772,
width = 950,
font = dict(
size = 10
),
)
print(layout)
fig = dict(data=[data_trace], layout=layout)
ply.offline.iplot(fig, filename='Test')
With the csv-file looking like this:
Source;Target;Value;Color;Node, Label
0;2;2958.5;#262C46;Test 1
0;2;236.7;#262C46;Test 2
0;2;1033.4;#262C46;Test 3
0;2;58.8;#262C46;Test 4
0;2;5.2;#262C46;Test 5
0;2;9.4;#262C46;Test 6
0;2;3.4;#262C46;Test 7
It seems to run fine, with the various outputs looking right at a first glance, but the final output from ply.offline.iplot(fig, filename='Test') just shows a large blank field:
The terminal looks like this after having run all the cells in the notebook once:
Can someone please point me to where I am going wrong here?
edit: I also posted this question on the plotly forums: https://community.plot.ly/t/no-output-from-plotly-offline-iplot/8086 -
I have had similar issues with plotly offline in Jupyter in the past - sometimes it's surprisingly inconsistent when/why the plots fail to appear. It may be worth a try starting with an increased data rate limit.
jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
For me helped change notebook to Trusted (this enabled Javascript and give plotly way to build graph into the jupyter notebook.).
This option you can found here:
I tried all the solutions suggested here, but none of them worked for me. What solved the issue was adding:
import plotly.io as pio
pio.renderers.default='notebook'
and also using fig.show("notebook") rather than simply fig.show(), as suggested here.
When using Google Colab, include the snippet -
import plotly.io as pio
pio.renderers.default = 'colab'
Or use the overall import statements as -
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import plotly.io as pio
pio.renderers.default = 'colab'
from plotly.offline import init_notebook_mode, iplot
This will set the rendering to Colab style and the plots will be displayed.
Hope this helps.
I can get the correct display with jupyter notebook server (without any additional options), but get a blank block
with jupyter lab server. Related version info:
$ jupyter lab --version
0.35.5
$ jupyter notebook --version
5.7.8
$ python -c "import plotly; print(plotly.__version__)"
3.10.0
So for those who are using JupyterLab, to properly display the offline plotly graphs in JupyterLab, we need to install the plotly-extension with following commands (following is excerpted from a related answer):
$ jupyter labextension install #jupyterlab/plotly-extension
$ jupyter labextension list
$ jupyter lab build
If none of these answers worked for you. Try this one
just do this in conda prompt opened with administrator permission
pip install pip --upgrade
conda upgrade notebook or pip install notebook --upgrade
conda install -c conda-forge ipywidgets or pip install ipywidgets
You need to have the latest versions of jupyter notebook and ipywidgets.
I have myself encountered a similar issue, with a sunburst plot. The blank plot was due to invalid data. I would have expected to get an error at runtime, but it appears that in some rare cases, no error is raised, and a blank plot is displayed instead.
Therefore, check your data validity, or perform a test with dummy data provided on plotly doc, in order to test if the problem comes from data or plotly/notebook interface.
From the quickstart in the README
This displays a figure, while none of the other answers here worked for me:
import plotly.graph_objs as go
fig = go.FigureWidget()
# Display an empty figure
fig
This (in a new cell) modifies the above plot with a bar and line chart:
# Add a scatter chart
fig.add_scatter(y=[2, 1, 4, 3])
# Add a bar chart
fig.add_bar(y=[1, 4, 3, 2])
# Add a title
fig.layout.title = 'Hello FigureWidget'
If that doesn't work, make sure your install is good, e.g. pip install --user --upgrade plotly if you installed with pip
Some of above methods did work for me. But I solve this kind of problem untimately according to this discussion and the official troubleshooting guide.
Step 1:
Close your jupyter lab. Then, uninstall plotly and some extensions.
$ conda remove plotly
$ jupyter labextension uninstall jupyterlab-plotly
$ jupyter labextension uninstall plotlywidget
Step2: Open terminal from the same environment as JupyterLab was launched to rebuild jupyter lab.
$ jupyter lab build
Step 3: Reinstall plotly and jupyter lab extensions with same versions
$ conda install plotly
$ jupyter labextension install jupyterlab-plotly
$ jupyter labextension install plotlywidget
Above precedures work fine for me in jupyter lab. I think we can try same precedures like it in jupyter notebook.
On my side the culprit was the "Darker Jupyter" addon I was using on firefox.
include these lines:
from plotly.offline import plot, iplot, init_notebook_mode
import plotly.graph_objs as go
init_notebook_mode(connected=True)
works for me
My response might be a little too late, but along with Plotly its also important to import plotly.graph.
These are the packages you need to import. I was getting the blank outputs too, and this worked for me.
from plotly.offline import plot, iplot, init_notebook_mode
import plotly.graph_objs as go
init_notebook_mode(connected=True)
I had almost a similar issue while trying to plot a heatmap in colab, for me the below solution helped:
import plotly.graph_objs as go
from plotly.offline import iplot
import chart_studio.plotly as py
# these two lines are what allow your code to show up in a notebook
import plotly.io as pio
pio.renderers.default='colab'
corr = data.corr()
trace = go.Heatmap(z=corr.values,
x=corr.index.values,
y=corr.columns.values)
data=[trace]
iplot(data, filename='basic-heatmap')

Categories