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')
Related
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.
With this script , it is open 2 dashboards and so 2 graphs
How i can modify it to see all on the same graph ?
dataframe:
df = pd.DataFrame( df_abs.to_numpy()[:, 1:].T).reset_index().melt(id_vars="index")
fig = px.line(df, x="index", y="value", color="variable")
fig.show()
script dot plotly:
df_abs = pd.DataFrame(df_abs.loc[outlier].iloc[1:]).reset_index().melt(id_vars="index")
fig = px.line(df_abs, x="index", y="value", color="variable")
fig.show()
df = pd.DataFrame( df_abs.to_numpy()[:, 1:].T).reset_index().melt(id_vars="index")
fig = px.line(df, x="index", y="value", color="variable")
fig.show()
You need to use plotly.graph_objects instead of plotly.express.
plotly.express is great for quick plots but it is somewhat limited compared to plotly.graph_objects.
Here is a dummy example using 2 dataframes to make it similar to your case.
import plotly.graph_objects as go
import plotly.express as px
df1 = px.data.gapminder().query("country in ['Canada']")
df2 = px.data.gapminder().query("country in ['Italy']")
fig = go.Figure()
fig.add_trace(go.Scatter(x=df1["lifeExp"], y=df1["gdpPercap"], mode='lines', name='Canada'))
fig.add_trace(go.Scatter(x=df2["lifeExp"], y=df1["gdpPercap"], mode='lines', name='Italy'))
fig.show()
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 using plotly Express density_heatmap and i'm trying to update manually the name of the legend (here the color continuous scale). I tried with labels, update_layout but it looks like i can't remove the 'sum of' or 'count' etc from the legend.
Here i modified example from plotly:
import plotly.express as px
dft = px.data.iris()
figt = px.density_heatmap(dft, x="sepal_width", y="sepal_length", z='sepal_length',
labels=dict(z='sepal_length'))
figt.show()
Is there a way to remove this sum of?
Thanks in andvance
You can use:
figt.update_layout(coloraxis_colorbar_title_text = 'your title')
Plot:
Complete code:
import plotly.express as px
dft = px.data.iris()
figt = px.density_heatmap(dft, x="sepal_width", y="sepal_length", z='sepal_length',
labels=dict(z='sepal_length'))
figt.update_layout(coloraxis_colorbar_title_text = 'your title')
figt.show()
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.