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')
Related
This question already has answers here:
Plotly: How to display charts in Spyder?
(2 answers)
Closed 8 days ago.
The following code yields a graph.
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
import plotly, plotly.express as px
arr = np.array(np.arange(stop=257, start=1).reshape(-1,4,4))
dfs = [pd.DataFrame(i, index=["row1", "row2", "row3", "row4"], columns=["col1", "col2", "col3", "col4"])for i in arr]
plt.plot(dfs[1])
plt.show()
but the following does not
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
import plotly, plotly.express as px
arr = np.array(np.arange(stop=257, start=1).reshape(-1,4,4))
dfs = [pd.DataFrame(i, index=["row1", "row2", "row3", "row4"], columns=["col1", "col2", "col3", "col4"])for i in arr]
px.line(dfs[1],x=dfs[1].index, y="col1").show()
clarification: both codes show plots when run in terminal but I can only see plot from matplotlib when these codes are run in spyder (there spyder tab "plots" only contains plot from matplotlib).
That's because in your second code, you're calling plotly.express.line to make a plotly plot (which is interactive) and I don't think Spyder can handle that.
Plotly's Python graphing library makes interactive,
publication-quality graphs.
You have at least, three choices/workarounds:
Either (1) use Jupyter Notebook or Jupyterlab.
Or (2) in Spyder, make the plot static (as well as your matplotlib plot) by adding these two lines :
import plotly.io as pio
pio.renderers.default='svg'
Or (3), always in Spyder, set your default Internet browser as the renderer :
import plotly.io as pio
pio.renderers.default='browser'
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:
Trying to create a simple Box Plot using Google Colab for my Intro Python class. It is not appearing as I would like it. You can see my code and output below. I read in a file on NBA statistics, and my box plot would be based on a variable called "SHOT_CLOCK".
So far what I have:
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv('file path')
plt.boxplot(df['SHOT_CLOCK'], vert=False)
plt.title('Box Plot for SHOT_CLOCK')
plt.xlabel('Shot Clock')
plt.show()
Output:
Edit
In your example you are passing a Series object, try this way
plt.figure()
plt.title('Box Plot for SHOT_CLOCK')
plt.xlabel('Shot Clock')
df.boxplot(column='SHOT_CLOCK')
Once you add the following Import to your code it will work:
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
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.
Emphasis : I am looking for a way to display multiple tables or charts from a cell.
I have the following code where I have a table and a chart (and a few more) that I would like to display all those visuals in the out put shell after running it.
I tried importing matplotlib and plt.show() but they don't seem to work.
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
tab = [[49.0,35.5,26.7,17.5], [46.7,34.0,26.0,17.1]]
tab = list(map(list, zip(*tab)))
tab_DataFrame = pd.DataFrame(tab, columns=["Mass(g)", "Volume(mL)"])
tab_DataFrame.head()
plt.show()
ax1 = tab_DataFrame.plot.line(x="Mass(g)", y="Volume(mL)",style='-o')
plt.show()
Thanks in advance.