How to display plotly outputs in google collaboratory notebooks? - python

I searched whole day how to display the outputs of plotly plots in google colaboratory jupyter notebooks. There is a stackoverflow question and also official tutorial from google colaboratory but both of them did not work for me.
official link:
https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=hFCg8XrdO4xj
stackoverflow question:
Plotly notebook mode with google colaboratory
https://colab.research.google.com/drive/14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f#scrollTo=8RCjUVpi2_xd
The built-in google colaboratory plotly version is 1.12.12.
Test plotly version
import plotly
plotly.__version__
1.12.12
Load libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
Mount google drive
from google.colab import drive
drive.mount('/content/drive')
dat_dir = 'drive/My Drive/Colab Notebooks/data/'
Official google colaboratory method (FAILED)
# https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=hFCg8XrdO4xj
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)
Test official suggestion (FAILED)
import plotly.plotly as py
import numpy as np
from plotly.offline import iplot
from plotly.graph_objs import Contours, Histogram2dContour, Marker, Scatter
enable_plotly_in_cell()
x = np.random.randn(2000)
y = np.random.randn(2000)
iplot([Histogram2dContour(x=x, y=y, contours=Contours(coloring='heatmap')),
Scatter(x=x, y=y, mode='markers', marker=Marker(color='white', size=3, opacity=0.3))], show_link=False)
Stackoverflow Bob Smith Method
# https://stackoverflow.com/questions/47230817/plotly-notebook-mode-with-google-colaboratory
def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
<script>
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-1.5.1.min.js?noext',
},
});
</script>
'''))
Test Bob Smith method (FAILED)
# https://colab.research.google.com/drive/14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f#scrollTo=8RCjUVpi2_xd
import plotly.plotly as py
import numpy as np
from plotly.offline import init_notebook_mode, iplot
from plotly.graph_objs import Contours, Histogram2dContour, Marker, Scatter
configure_plotly_browser_state()
init_notebook_mode(connected=False)
x = np.random.randn(2000)
y = np.random.randn(2000)
iplot([Histogram2dContour(x=x, y=y, contours=Contours(coloring='heatmap')),
Scatter(x=x, y=y, mode='markers', marker=Marker(color='white', size=3, opacity=0.3))], show_link=False)
Questions
How to display the plotly output in google colaboratory?
Is is possible ? If so which version of plotly or cufflinks is working for you?
If it is not possible to display, can we save the output file as .html in our google drive and open them manually and see them?
I appreciate your help.

plotly version 4.x
As of version 4, plotly renderers know about Colab, so the following is sufficient to display a figure in both Colab and Jupyter (and other notebooks like Kaggle, Azure, nteract):
import plotly.graph_objects as go
fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
fig.show()
plotly version 3.x
I was also struggling to display the plotly graphs in Google colab and stumbled upon this thread where you explained the problems with different solutions over the net. Feelings are the same for each one of the solutions. Finally, my search ended when I came across this video.
I followed his approach (might be similar to the ones you already tried) and this worked for me.
Upgrade plotly in colab thru !pip install plotly --upgrade and restart runtime as suggested.
Comment the upgrade option before re-running your notebook
Define the function configure_plotly_browser_state()
Invoke plotly libraries
Call function and notebook mode like below in every cell where you want to call iplot
configure_plotly_browser_state()
init_notebook_mode(connected=False)
iplot(XXXXXX)
Just import plotly libraries
Please let me know if this helps :)

Try to use renderer="colab" as shown below:
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displayed with the 'colab' Renderer"
)
fig.show(renderer="colab")

Add line '%matplotlib inline' at the beginning of notebooks
Refer below link:
https://github.com/jupyter/notebook/issues/3523

use
import plotly.io as pio
pio.renderers.default = "colab"
it works for me on plotly version 5.5.0

Use plot and not iplot ...it took me a while for this one to figure out. You can the plot both to the notebook and to gdrive.

Related

Plotly barplot not rendering fine in streamlit app

When rendering a plotly barplot with fig.show(), I get the plot exactly the way I developed it. But when I render it using streamlit's st.plotly_chart(), it gets with another appearance (without the bar labels).
This is how it should be (the plot I get when using fig.show()):
How it renders with st.plotly_chart() (dark theme):
And in light theme:
My code:
import pandas as pd
import streamlit as st
import plotly.express as px
df = pd.read_excel('file.xlsx', sheet_name='Current_Base')
fig = px.histogram(df,
x='number',
text_auto=True
)
fig.show()
st.plotly_chart(fig)
My relevant settings:
- os: macOS Monterey 12.1
- libs:
streamlit 1.3.1
plotly 5.5.0
Could anyone help me with this issue?

plotly does not show the plots in google colaboratory

I have a dataframe named "Actuals", indexed by time. This is how I want to plot the Load column.
fig = go.Figure([go.Scatter(x=Actuals.index, y= Actuals['Load (kW)'])])
fig.show()
When I run this part, it executes without rising any error. but it doesn't display the figure. What is the issue and how can I resolve it?
I am using Google colaboratory
I should have added this line of code:
import plotly.io as pio
pio.renderers.default = 'colab'

Using plotly for a surface plot

I'm trying to plot the Surface plot using plotly command for the function f(x,y)=x+y.
The following is the code I use in Jupyter notebook
import numpy as np
x=np.linspace(-10,10,100)
y=np.linspace(-10,10,100)
X,Y=np.meshgrid(x,y)
Z=x+y
import plotly
import plotly.graph_objects as go
plotly.offline.init_notebook_mode()
trace=go.Surface(x=x,y=y,z=Z)
data=[trace]
fig=go.Figure(data=data)
plotly.offline.iplot(fig)
But unfortunately I'm only getting some thing like this:
Can someone please explain what I have done wrong ?
I figured it out!
I have put x instead of X in the go.Surface

Not able to load the proper 3D image using pyplot and cufflinks module in python

I am currently doing a data science and machine learning course where I attended a lecture on plotly and cufflinks. I am currently using pycharm and trying to plot a 3 dimensional image called 'Surface Plot'. When I run the code, I am getting the output as a blank 3 dimensional figure without any image in it. I have written the code ,attached the output that I am getting and the actual output. How do I get the actual output with the 3D image?
code:
import plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import cufflinks as cf
print(__version__)
init_notebook_mode(connected=True)
cf.go_offline()
df = pd.DataFrame(np.random.randn(100,4),columns='A B C D'.split())
df2 = pd.DataFrame({'x':[1,2,3,4,5],'y':[10,20,30,20,10],'z':[5,4,3,2,1]})
trace = go.Surface(x=df2['x'],y=df2['y'],z=df2['z'])
data = [trace]
fig = go.Figure(data=data)
py.offline.plot(fig)
This is the output I am getting
This is the actual output:

save my offline plotly plot as html file locally

In my jupyter notebook, I made an offline interactive plot with plotly. I'm trying to save this interactive plot as a html file locally.
Below is my code. However, I cannot find my file I intended to save anywhere. Does anyone know what I did wrong?
Thanks a lot.
py.offline.init_notebook_mode(connected=True)
import plotly as py
import plotly.graph_objs as go
import numpy as np
y = np.random.randn(500)
data = [go.Histogram(y=y)]
py.offline.iplot(data, filename='myplot.html')
You're using iplot which is the interactive plot method that plots it in the Jupyter notebook for you to see. If you want to generate the HTML file change iplot to plot and it will create it for you:
import plotly as py
py.offline.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import numpy as np
y = np.random.randn(500)
data = [go.Histogram(y=y)]
py.offline.plot(data, filename='myplot.html')
Plotly 4.x:
Use to_html or write_html.
import plotly.io as pio
import plotly.express as px
df = px.data.iris()
fig = px.bar(df, x='sepal_length', y='sepal_width')
pio.write_html(fig, file='iris.html')
reference
Moreover, if you are using Cufflinks or any other offline mode, you can export the html interactive graph in the following way:
# Original cufflinks call to plot the graph within a Jupyter Notebook:
plyo.iplot(pv.iplot(asFigure=True,kind='bar',xTitle='REF',yTitle='Defects',title='Kind of Defects',barmode='stack'))
# Export to html file
fig =pv.iplot(asFigure=True,kind='bar',xTitle='REF',yTitle='Defects',title='Kind of Defects',barmode='stack')
pio.write_html(fig, file='defects.html')

Categories