Unable to create png image with plotly kaleido - python

I have the plotly code as below with dataframes.
I'm unable to create an image with the below code.
I see the same working in other system. what could be the issue ??
SampleData: df3
,ts,windSpeed,windDirection,tsDate,tsYear,tsMonth,tsDay,tsHour,powerGenKW,powerPerc,powerPercSq,dtCnt,iAmp,iPerUnit,iPerUnitSq,tInf
87955,2013-06-16 19:00:00,0.075,263.5,2013-06-16,2013,6,16,19,0.0,0.0,0.0,3665,0.0,0.0,0.0,0.6303445045509951
87200,2013-05-16 08:00:00,0.153,74.0,2013-05-16,2013,5,16,8,0.0,0.0,0.0,3634,0.0,0.0,0.0,0.6303445045509951
81201,2012-09-08 09:00:00,0.212,21.2,2012-09-08,2012,9,8,9,0.0,0.0,0.0,3384,0.0,0.0,0.0,0.6303445045509951
65785,2010-12-06 01:00:00,0.242,345.0,2010-12-06,2010,12,6,1,0.0,0.0,0.0,2742,0.0,0.0,0.0,0.6303445045509951
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
df4_fig = get_output1(df3)
fig1 = px.scatter(df4_fig, x="day", y="p_ma")
fig2 = px.line(df4_fig, x="day", y="p_ma")
fig3 = go.Figure(data=fig1.data + fig2.data)
subfig = make_subplots()
subfig.add_traces(fig3.data)
subfig.update_layout(autosize=False, width=1000, height=600, xaxis=dict(tick0=0, dtick=10),
title="Maximum Load in % as a function of period T based on 16 years data",
xaxis_title="Length of moving average (Days)", yaxis_title="Max windfarm load (%)")
subfig.write_image(os.path.join(output_filepath, 'Output1.png'), engine='kaleido')

Related

Plotly Express Overlay Two Line Graphs

I know that it is easy to overlay plots using Plotly Go.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[1,1,2])])
fig.show()
However, I would like to accomplish same task using Poltly Express. Is there a way to accomplish such a task in Plotly Express?
You can do it with add_traces
import pandas as pd
import numpy as np
import plotly.express as px
data = {'x':[1,2,3], 'y':range(3)}
df1 = pd.DataFrame(data)
data = {'x':[4,5,6], 'y':range(4,7)}
df2 = pd.DataFrame(data)
fig1 = px.line(df1, x='x', y='y', color_discrete_sequence=['red'])
fig2 = px.line(df2, x='x', y='y', labels='green', color_discrete_sequence=['green'])
fig1.add_traces(
list(fig2.select_traces())
)
name = ['red','green']
for i in range(len(fig1.data)):
fig1.data[i]['name'] = name[i]
fig1.data[i]['showlegend'] = True
fig1.show()
However, I prefer to use go plots, which are easier.

ipywidgets tab not displaying every time

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

plot line over heatmap

hello im trying to make a heatmap with btc asks and bids, this graph will have a line representing the close price. im using :
plotly.expres as px
plotly.graph_objects as go
the code is :
go.Figure(go.Heatmap(x=df3["timestamp"], y=df2["asks"], z=df["baseVolume"])
px.line(df3, x="timestamp", y="close") ## not working
fig.show()
graph output
Since no data is presented, I have used the heatmap in the official reference as an example for my code. Since the heatmap seems to deal with categorical variables, we need to add two axes for the y-axis, so we add a subplot. If we set the line chart to the added second axis, the heatmap and the line chart will be superimposed.
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import datetime
import numpy as np
np.random.seed(1)
programmers = ['Alex','Nicole','Sara','Etienne','Chelsea','Jody','Marianne']
base = datetime.datetime.today()
dates = base - np.arange(180) * datetime.timedelta(days=1)
z = np.random.poisson(size=(len(programmers), len(dates)))
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Heatmap(
z=z,
x=dates,
y=programmers,
colorscale='Viridis'))
fig.add_trace(go.Scatter(
mode='lines',
x=dates,
y=np.linspace(0,5, len(dates)).cumsum(),
line=dict(color='red',width=2)), secondary_y=True,)
fig.update_layout(
title='GitHub commits per day',
xaxis_nticks=36)
fig.show()

How to add several graphs to a single tab using plotly express with python

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.

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