ipywidgets tab not displaying every time - python

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

Related

Plotly python add annotation to display all column values at every point

I am trying to plot all column values at each point when we hover over a data point in plotly
My code is as follows
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
import pandas as pd
# data
pio.templates.default = "plotly_white"
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df_s = df[['Date','AAPL.Open','AAPL.High','AAPL.Low','dn','mavg'
]]
df_s = df_s.set_index('Date')
df_s.tail()
cols = df_s.columns
ncols = len(cols)
# subplot setup
fig = make_subplots(rows=ncols, cols=1, shared_xaxes=True)
for i, col in enumerate(cols, start=1):
fig.add_trace(go.Scatter(x=df_s[col].index, y=df_s[col].values, name=df_s[col].name), row=i, col=1)
fig.update_layout(
autosize=False,
width=1200,
height=800,)
fig.show()
Currently when I hover over the datapoint it shows value for that column alone. I am interested in seeing
Values for 'Date','AAPL.Open','AAPL.High','AAPL.Low','dn','mavg' these columns at a particular row whenever I hover over anyplot
I tried add_annotations with no luck. Is there a way of doing it? Thank you in advance
As #Marco_CH pointed out, this exact feature doesn't exist in Plotly. However, you can try using a unified hovermode on the x-axis so there is only one hoverbox, and remove the date from each hovertemplate since it's already shown at the top of the hoverbox.
import pandas as pd
import plotly.express as px
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df1 = df.melt(id_vars=['Date']+list(df.keys()[5:]), var_name='AAPL')
fig = px.line(df1, x='Date', y='value', color='AAPL' )
## remove date from each hovertemplate
for fig_data in fig.data:
fig_data['hovertemplate'] = fig_data['hovertemplate'].replace("<br>Date=%{x}","")
fig.update_layout(hovermode="x unified")
fig.show()
No, this doesn't work. There is an open issue for this:
https://github.com/plotly/plotly.js/issues/4755
And it doesn't seem that this will come soon. You have to decide between your way and something like:
import pandas as pd
import plotly.express as px
pio.templates.default = "plotly_white"
df_s = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df_s = df_s.melt(id_vars=["Date"]+list(df.keys()[5:]), var_name="AAPL")
fig = px.line(df_s, x="Date", y="value", color="AAPL")
fig.update_layout(
autosize=False,
width=1200,
height=800,
hovermode="x")
fig.show()
Output:

Plotly time series multiplots

I need help with plotly - plotting time series interactive charts with multiple lines in each subplot. My data looks like this:
import pandas as pd
df1 = pd.DataFrame(np.random.randint(100, size=(100,6)), columns=['A_red', 'A_blue', 'B_red', 'B_blue', 'C_red', 'C_blue'])
Next I want to do:
import plotly.express as px
fig1 = px.line(df, y=['A_red', 'A_blue'], color=['red', 'blue'])
fig2 = px.line(df, y=['B_red', 'B_blue'], color=['red', 'blue'])
fig3 = px.line(df, y=['C_red', 'C_blue'], color=['red', 'blue'])
figs = [fig1, fig2, fig3]
figs.show()
I cant get any plot to load in spyder (inline or in the plots tab), also how do I map colors to different lines?
Thanks
Spyder doesn't support interactive graphs. You have 2 options to show the plots: either show them in a browser, or display them as static plots. To render them in a browser where they will be interactive:
import plotly.io as pio
pio.renderers.default = 'browser'
To render them in the Spyder plots pane as a static chart:
import plotly.io as pio
pio.renderers.default = 'svg'
You need to delete the color argument from the px.line() calls or it will throw an error. Given the way your data is formatted, you won't be able to easily use the color argument. To change the colors of the lines:
fig1 = px.line(df, y=['A_red', 'A_blue'])
fig1.data[0].line.color = 'green'
fig1.data[1].line.color = 'purple'
fig1.show()
Not that you asked for it, but in order to get
figs = [fig1, fig2, fig3]
figs.show()
to work, you will need to do the following:
figs = [fig1, fig2, fig3]
for fig in figs:
fig.show()
To plot all 3 in a single figure you will first need to transform the data from wide to long:
df = pd.DataFrame(np.random.randint(100, size=(100,6)),
columns=['A_red', 'A_blue', 'B_red', 'B_blue', 'C_red', 'C_blue'])
df['x'] = df.index
df_long = df.melt(id_vars='x', var_name='letter')
df_long['group'] = df_long.letter.str.split('_', expand=True)[1]
df_long['letter'] = df_long.letter.str.split('_', expand=True)[0]
Then you can do the following:
facet_fig = px.line(df_long, y='value', x='x', color='group', facet_row='letter')

Unable to create png image with plotly kaleido

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')

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