Home > Mobile >  Plotly time series multiplots
Plotly time series multiplots

Time:12-04

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

CodePudding user response:

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

enter image description here

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

enter image description here

  • Related