Show plotly plots in a auto-generated Jupyter notebook - python

I'm trying to generate a series of notebooks with plotly plots through a script. Problem is plotly plots don't show even after being executed. In the example below I the matplotlib plot shows up just fine, but for the ploly visualiztion to show up I have to re-run it manually.
Is there way to have the plotly plot be saved in the notebook so that it doesn't need to be re-run?
from nbconvert.preprocessors import ExecutePreprocessor
import nbformat as nbf
nb = nbf.v4.new_notebook()
# Make a few visualizations
code = """\
%pylab inline
hist(normal(size=2000), bins=50);"""
code2 = """\
%pylab inline
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.show()
"""
nb['cells'] = [
nbf.v4.new_code_cell(code),
nbf.v4.new_code_cell(code2),
]
# Execute the notebook
ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
ep.preprocess(nb)
with open('test.ipynb', 'w') as f:
nbf.write(nb, f)

Related

Python 3 does not show the barchart

I am trying to make this bargraph appear in the python run screen. But for some reason, it does not show the graph on the screen. However, if I put this code on the google online coding website, it shows the bar graph fine. Can anyone let me know what the problem is?
import pandas as pd
import plotly.express as px
df = pd.read_csv("Diversity2.csv")
df = df.groupby(['School','White'], as_index=False)[['School']].sum()
# df = df.groupby(['School','White']).sum().plot(kind='bar')
df['White']=df['White'].astype(float)
# df.plot(kind='bar', x='School', y='White', figsize=(20,10))
barchart = px.bar(
data_frame=df,
x="School",
y="White",
color="School",
opacity=0.9,
orientation="v",
barmode='overlay')
barchart.show()

How to show the figure in an interactive 3D plot using Plotly in Colab?

I have developed a 3D plot that is updated with a slider in Jupyter Notebook. I am using the following code structure:
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
import plotly.offline as py
from ipywidgets import interactive, VBox
import ipywidgets as widgets
from google.colab import output
output.enable_custom_widget_manager()
dataFrame = pd.DataFrame(data, columns=objectives)
fig = go.FigureWidget(
go.Scatter3d(
x=fdf[objectives[0]],
y=fdf[objectives[1]],
z=fdf[objectives[2]],
hovertemplate= objectives[0] + " = %{x}<br>" + objectives[1] + " = %{y}<br>" + objectives[2] + " = %{z}<extra></extra>",
mode ='markers',
marker = {'color' : colors}
))
freq_slider = interactive(update_color,
obj1_w=(0, 0, 0),
obj2_w=(0, 0, 0),
obj3_w=(0, 0, 0))
vb = widgets.VBox((fig, freq_slider))
vb.layout.align_items = 'center'
vb
In Jupyter Notebook, it works perfectly... The slider updates the 3D plot, but in Colab, fig does not appear because the show() function is needed.
The following picture illustrates the 3D plot using Vbox that appears in Jupyter Notebook:
In Colab, the fig does not appear, only if I use the show() function, but it does not update when I use the slider.
Does anyone know how to plot the fig in this case? If it is not possible, is there another way to achieve the same result in Colab?

Plotly Library do not showed anything

I tried to plot a scatter plot using plotly libraries.
import chart_studio.plotly as py
import plotly.offline as pyoff
import plotly.graph_objs as go
#plot monthly sales
plot_data = [
go.Scatter(
x=df['date'],
y=df['qty'],
)
]
plot_layout = go.Layout(
title='Montly Sold'
)
fig = go.Figure(data=plot_data, layout=plot_layout)
pyoff.iplot(fig)
fig.show()
The output is just a blank
How to overcome this problem?
I don't have the chart_studio installed but it seems it wasn't used anyway in your code. So after commenting chart_studio import and adding some data to your dataframe I can successfully run your code in my IDE (Eclipse). However it was opening two windows with the same plot so I had to remove one of the two last lines so just one window opens.
Then I tried your code in local Jupyter Notebook and in hosted Google CoLab and it works fine with the following code:
import plotly.graph_objs as go
import pandas as pd
import numpy as np
rng = pd.date_range('2015-02-24', periods=5, freq='T')
df = pd.DataFrame({ 'date': rng, 'qty': np.random.randn(len(rng)) })
#plot monthly sales
plot_data = [
go.Scatter(
x=df['date'],
y=df['qty'],
)
]
plot_layout = go.Layout(
title='Montly Sold'
)
fig = go.Figure(data=plot_data, layout=plot_layout)
fig.show()
Or you could leave the import plotly.offline as pyoff and use pyoff.iplot(fig) instead of fig.show() which also works fine.
Note: Running your code in Jupyter Notebook for the first time after (re-)starting you computer can take quite some time to generate and show a plot.

Matplotlib to plotly offline

I have some matplotlib graphs that need to be viewed offline in a browser, I was using MPLD3 to render them before, but given the need to view the plots without an internet connection, I'm considering using plotly. Is there a way to view matplotlib plotly graphs offline?
A minimal example of converting a matplotlib figure to plotly would look like this.
import matplotlib.pyplot as plt
import plotly
import plotly.plotly as py
import plotly.tools as tls
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9], "o")
plotly_fig = tls.mpl_to_plotly(fig)
plotly.offline.plot(plotly_fig, filename="plotly version of an mpl figure")
Just posting this as the documentation was somewhat hard to follow.
import plotly.tools as tls
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
x = np.random.random(100) ### toy data
y = np.random.random(100) ### toy data
## matplotlib fig
fig, axes = plt.subplots(2,1, figsize = (10,6))
axes[0].plot(x, label = 'x')
axes[1].scatter(x,y)
## convert and plot in plotly
plotly_fig = tls.mpl_to_plotly(fig) ## convert
iplot(plotly_fig)
How about this page at Section Offline Use
BTW: You can also write a static image file as described here
import plotly.io as pio
import plotly.graph_objs as go
fig = go.Figure()
# Do some fig.add_scatter() stuff here
pio.write_image(fig, 'fig1.png')

Python Plotly heatmap subplots - remove internal y-axis numbers and ticks

How do I remove the numbers and ticks from the internal y-axis in the Plot.ly heatmap subplot graph below? Both plots share the same y-axis range so there is no reason to show both.
import plotly.plotly as py
import plotly.graph_objs as go
from plotly import tools
import pandas as pd
import numpy as np
dfl = []
dfl.append(pd.DataFrame(np.random.random((100,100,))))
dfl.append(pd.DataFrame(np.random.random((100,100,))))
fig = tools.make_subplots(rows=1, cols=len(dfl) ,print_grid=False);
for index, a in enumerate(dfl):
sn = str(index)
data = go.Heatmap(
z=a.values.tolist(),
colorscale='Viridis',
colorbar=dict(title='units'),
)
fig.append_trace(data, 1, index+1)
fig['layout']['xaxis'+str(index+1)].update(title='xaxis '+str(index))
fig['layout']['yaxis1'].update(title='y-axis')
fig['layout'].update(height=600, width=800, title='heatmap subplots')
py.iplot(fig)
Simply pass the setting 'shared_yaxes=True' to the tools.make_subplots function call, that is:
fig = tools.make_subplots(rows=1, cols=len(dfl) ,print_grid=False, shared_yaxes=True)
Updated answer for newer versions of Plotly. Based upon the v4 migration guide.
Differences include
calling the make_subplots function from the plotly.subplots library, instead of plotly.tools, and
using fig.show inplace of py.iplot to show the figure in Jupyter.
The code below was tested in Plotly version 5.1.0 using Jupyter Notebook.
import plotly
import plotly.graph_objs as go
import pandas as pd
import numpy as np
dfl = []
dfl.append(pd.DataFrame(np.random.random((100,100,))))
dfl.append(pd.DataFrame(np.random.random((100,100,))))
fig = plotly.subplots.make_subplots(rows=1, cols=len(dfl) ,print_grid=False, shared_yaxes=True);
for index, a in enumerate(dfl):
sn = str(index)
data = go.Heatmap(
z=a.values.tolist(),
colorscale='Viridis',
colorbar=dict(title='units'),
)
fig.append_trace(data, 1, index+1)
fig['layout']['xaxis'+str(index+1)].update(title='xaxis '+str(index))
fig['layout']['yaxis1'].update(title='y-axis')
fig['layout'].update(height=600, width=800, title='heatmap subplots')
fig.show()
The output:

Categories