【发布时间】:2022-02-06 01:30:18
【问题描述】:
我有 2 个时间序列数据帧,它们来自两个二维数组。这些数据帧的结构是:
生成示例数据帧
import pandas as pd
import numpy as np
date_range = pd.period_range('1981-01-01','1981-01-04',freq='D')
x = np.arange(8).reshape((4,2))
y = np.arange(8).reshape((4,2))
x = pd.DataFrame(x, index = date_range, columns = ['station1','station2'])
y = pd.DataFrame(y, index = date_range, columns = ['station1','station2'])
print(x)
station1 station2
1981-01-01 0 1
1981-01-02 2 3
1981-01-03 4 5
1981-01-04 6 7
目标
我想生成一个多图,其中 'x' 和 'y' 的值在同一个图上绘制为线,x 和 y 按颜色分割,但每个站有多个图的“行” .使用上面的示例代码,每个单独的图表将绘制不同的站列。
我尝试过的
我尝试了 seaborn 路线:首先将两个数据帧连接在一起 - 每个 df 代表一个变量,因此我将它们添加为键以在连接后命名这些变量。然后我使用了 melt 来对它们进行多重绘图:
df = pd.concat([x , y], keys = ['Var1', 'Var2'])
meltdf = df.melt(var_name = 'Station', value_name = 'Value', ignore_index = False)
print(meltdf)
Station Value
Var1 1981-01-01 station1 0
1981-01-02 station1 2
1981-01-03 station1 4
1981-01-04 station1 6
Var2 1981-01-01 station1 0
1981-01-02 station1 2
1981-01-03 station1 4
1981-01-04 station1 6
Var1 1981-01-01 station2 1
1981-01-02 station2 3
1981-01-03 station2 5
1981-01-04 station2 7
Var2 1981-01-01 station2 1
1981-01-02 station2 3
1981-01-03 station2 5
1981-01-04 station2 7
我想将 Var1 和 Var2 的值绘制为 station1 的同一图表上的线,station2 的相同,依此类推。我想保留日期作为索引,因为这些应该是时间序列图,“日期”沿 x 轴。我试过这个 non-working 代码(例如):
import seaborn as sns
sns.relplot(data=df, x = 'Var1', y = 'Var2', kind = 'line', hue = 'keys', row = 'Station')
我应该“双重融化” dfs 以将变量类型作为自己的 col 吗? concat + keys 步骤似乎不正确。
【问题讨论】:
标签: python pandas matplotlib seaborn