plotly does not show the plots in google colaboratory - python

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'

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?

Animated multiseries Line Graph using Plotly Express (Python)

I am trying to animate a multi series line graph using plotly. However after days of going through the documentation I still can't seem to find a solution.
Currently my code is as follows:
df = px.data.gapminder().query("continent=='Oceania' ")
fig = px.line(df, x="year" , y="lifeExp", color="country" , animation_frame="year", animation_group="lifeExp" , range_y=[68,84] , range_x=[1950,2010])
plot(fig)
This however generates and empty plot. Please help.
I am able to successfully generate a scatter plot and a bar graph using similar code.
For better understanding please view below link :
I have found an exact example of what I am looking for implemented in R.
https://plot.ly/r/cumulative-animations/#cumulative-lines-animation
For the empty plot, try changing the default renderer by adding this above your code:
import plotly.io as pio
pio.renderers.default = 'notebook'
There is some documentation on different renderers.

Printing image in r-markdown using matplotlib and python code

I am trying to run the python code using the R-Markdown file (RMarkdown to pdf).
What I achieved till now -
1- I am able to configure my python engine using knitr and reticulate library
2- I am able to execute my python codes.
What I tried -
1- I tried all the methods which are discussed in this forum, but nothing is working out.
2- I also tried to save the image,(as one of the posts here suggests), but that also is not working.
My problem -
1- When I am trying to plot a graph using matlplotlib and command plt.imshow() and plt.show(), it's not printing the image in the output. Rather it's showing the image in a separate window. You can see my results in the attached image.
Result_of_my_code
Here is my code
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{python}
import numpy as np
import os
import torch
import torchvision.datasets as dsets
import matplotlib.pyplot as plt
print(os.getcwd())
os.chdir('D:\\1st year\\Python codes\\CIFR Analysis\\self contained analysis')
print(os.getcwd())
train_mnist = dsets.MNIST("../data", train=True)
test_mnist = dsets.MNIST("../data", train= False)
print(len(train_mnist))
#print(train_mnist[0][0])
plt.imshow(train_mnist[0][0], cmap="gray")
#plt.savefig("trainzero.png")
plt.show()
```
Kindly, help me to fix this issue, as I want to compile my python codes using the R markdown file.
thanks
So with R Markdown, you have to do some things a little differently. In the following, I have a dataframe with two series created by concatenating them. The original plotting code in the Jupyter Notebook is as follows and just printed out the series.
# make a plot of model fit
train.plot(figsize=(16,8), legend=True)
backtest.plot(legend=True);
However, it does not work with way with R Markdown. Then with plotting, you always have to assign them, and with the code below, you get the same plot.
dfreg = pd.concat([reg, backtest], axis = 1)
ax = dfreg.plot(figsize=(16,8), legend = True)
ax1 = predictions.plot(legend=True)
plt.show()
This is common with other plotting functions like plot_acf() too.

How to display plotly outputs in google collaboratory notebooks?

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.

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