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.
Related
In googleColab, I am creting 3 tabs using ipywidgets, and filling them with plots from Plotly.
However it sometimes works, sometimes doesn't display the first plot:
Here is the code, and a link to github with COLAB example i created.
import ipywidgets as widgets
import pandas as pd
import plotly.express as px
df = px.data.gapminder()
fig0 = px.line(df.query("continent=='Africa'"), x="year", y="lifeExp", title='fig0')
fig1 = px.line(df.query("continent=='Oceania'"), x="year", y="lifeExp", title='fig1')
fig2= px.line(df.query("continent=='Europe'"), x="year", y="lifeExp", title='fig2')
figures = {"fig0": fig0,
"fig1": fig1,
"fig2": fig2}
sub_tab=[widgets.Output() for i in range(len(figures))]
tab = widgets.Tab(sub_tab)
for i, k in enumerate(figures):
tab.set_title(i,k)
with sub_tab[i]:
figures[k].show()
display(tab)
Not working:
Working:
#TRIAL FROM r-beginners comment: sometimes wont show tab1
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)
I have a script that producing 5 different graphs that I want to present in one web page.
I use python with plotly express and define pio.renderers.default = "browser".
The problem is that each graph is open in a new tab, and I want only one tab that I could share.
My script contains two separate data frames:
import pandas as pd
import plotly.express as px
import plotly.io as pio
pio.renderers.default = "browser"
df1=pd.read_csv('data1.csv')
df2=pd.read_csv('data2.csv')
fig = px.bar(df1,x1, y1,color='a',barmode='group')
fig.show()
fig = px.line(df2,x2, y2,color='b')
fig.show()
OK, you need to use plotly.subplots.make_subplots. I don't have your data, so I will use a simple data from plotly in the following code:
import plotly.express as px
from plotly.subplots import make_subplots
df = px.data.gapminder().query("country == 'Canada'")
fig1 = px.bar(df, x='year', y='pop')
fig2 = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
fig = make_subplots(rows=2, cols=1, shared_xaxes=False)
fig.add_trace(fig1['data'][0], row=1, col=1)
fig.add_trace(fig2['data'][0], row=2, col=1)
fig.show()
This will generate the following graph:
Side Note: Plotly.express shows figure in the browser by default, you don't have to specify it.
I have a plotly bar chart, from a dataframe:
fig = df.iplot(asFigure=True, kind='bar', barmode = 'relative')
py.iplot(fig)
Is it possible to turn one of the columns in the data frame into a line series?
The suggested link in the comments does have some valuable resources, but they won't answer your questions directly. iplot() uses a pandas dataframe as input, and produces a stacked barplot. Here's an approach that will let you do exactly that, albeit without using df.iplot()
First, the plot :
Now, the code
My suggestion builds on an example found at: plot.ly/pandas/bar-charts. As you'll see that's an example that builds on a pandas dataframe - just like df.iplot(). You can simply take a series or 'trace' out of the stacked bars and display it as a line by changing
go.Bar(x=df['x'],
y=df['y4'])
to:
go.Scatter(x=df['x'],
y=df['y4'])
I've also added a few elements to make it easier to display your results offline in a Jupyter notebook. Also note that I've changed the last line from py.iplot(fig, filename='pandas-bar-chart-layout') to just iplot(fig, filename='pandas-bar-chart-layout')
Complete snippet:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import pandas as pd
import numpy as np
N = 20
x = np.linspace(1, 10, N)
y = np.random.randn(N)+3
y2 = np.random.randn(N)+6
y3 = np.random.randn(N)+9
y4 = np.random.randn(N)+12
df = pd.DataFrame({'x': x, 'y': y, 'y2':y2, 'y3':y3, 'y4':y4})
df.head()
data = [
go.Bar(
x=df['x'], # assign x as the dataframe column 'x'
y=df['y']
),
go.Bar(
x=df['x'],
y=df['y2']
),
go.Bar(
x=df['x'],
y=df['y3']
),
go.Scatter(
x=df['x'],
y=df['y4']
)
]
layout = go.Layout(
barmode='stack',
title='Stacked Bar with Pandas'
)
fig = go.Figure(data=data, layout=layout)
# IPython notebook
iplot(fig, filename='pandas-bar-chart-layout')
answering to the last comment, I changed the code to include a loop like you asked.
Let me know if this helps:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import pandas as pd
import numpy as np
N = 20
x = np.linspace(1, 10, N)
y = np.random.randn(N)+3
y2 = np.random.randn(N)+6
y3 = np.random.randn(N)+9
y4 = np.random.randn(N)+12
df = pd.DataFrame({'x': x, 'y': y, 'y2':y2, 'y3':y3, 'y4':y4})
df.head()
data = []
for i in df.columns:
if i!= "x":
data.append(
go.Bar(
x=df['x'], # assign x as the dataframe column 'x'
y=df[i]
)
)
layout = go.Layout(
barmode='stack',
title='Stacked Bar with Pandas'
)
fig = go.Figure(data=data, layout=layout)
# IPython notebook
iplot(fig, filename='pandas-bar-chart-layout')
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: