绘制时间序列多图

Posted

技术标签:

【中文标题】绘制时间序列多图【英文标题】:Plotly time series multiplots 【发布时间】:2022-01-10 03:09:19 【问题描述】:

我需要关于 plotly 的帮助 - 在每个子图中绘制带有多条线的时间序列交互式图表。我的数据如下所示:

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

接下来我想做的:

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

我无法在 spyder 中加载任何绘图(内联或绘图选项卡),我如何将颜色映射到不同的行?

谢谢

【问题讨论】:

【参考方案1】:

Spyder 不支持交互式图表。您有 2 个选项来显示图:在浏览器中显示它们,或者将它们显示为静态图。在浏览器中呈现它们,它们将是交互的:

import plotly.io as pio
pio.renderers.default = 'browser'

要将它们在 Spyder 绘图窗格中呈现为静态图表:

import plotly.io as pio
pio.renderers.default = 'svg'

您需要从px.line() 调用中删除颜色参数,否则会引发错误。鉴于您的数据格式,您将无法轻松使用颜色参数。要更改线条的颜色:

fig1 = px.line(df, y=['A_red', 'A_blue'])
fig1.data[0].line.color = 'green'
fig1.data[1].line.color = 'purple'
fig1.show()

不是你要求的,而是为了得到

figs = [fig1, fig2, fig3]
figs.show()

要工作,您需要执行以下操作:

figs = [fig1, fig2, fig3]
for fig in figs:
    fig.show()

要将所有 3 个都绘制在一个图中,您首先需要将数据从宽转换为长:

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]

然后您可以执行以下操作:

facet_fig = px.line(df_long, y='value', x='x', color='group', facet_row='letter')

【讨论】:

嗨,Cazman,这解决了我的问题,只是多了一个问题:``` for figs in figs: ``` 仍然在 3 个单独的浏览器选项卡中绘制图表。如何让它加载到 1 个标签中? 编辑描述了如何按字母刻面图。如果这是仪表板之类的一部分,您还可以在单​​个页面中呈现多个图。

以上是关于绘制时间序列多图的主要内容,如果未能解决你的问题,请参考以下文章

matplotlib的基本用法——subplot绘制多图

ggplot2绘制多图

echarts 点击方法总结,点任意一点获取点击数据,举例说明:在多图联动中点击绘制标线

多图给出空白 PDF,数据维度错误

在 Seaborn 多图中调整 y 轴

ArcGIS制图——多图层道路压盖处理