gpt4 book ai didi

python - 具有重复序列的 Pandas 数据帧 : How to do a spaghetti plot?

转载 作者:太空宇宙 更新时间:2023-11-03 17:37:40 33 4
gpt4 key购买 nike

我得到的数据类似于以下数据:pandas.DataFrame:

                                  diff_1       diff_2
1949-01-01 06:00:00 -0.555 -0.123
1949-01-01 07:00:00 -0.654 0.230
1949-01-02 06:00:00 -0.879 0.012
1949-01-02 07:00:00 -0.459 0.672
1949-01-03 06:00:00 -0.588 0.980
1949-01-03 07:00:00 -0.068 0.375
1950-01-01 06:00:00 -0.654 0.572
1950-01-01 07:00:00 -0.544 0.092
1950-01-02 06:00:00 0.374 -0.275
1950-01-02 07:00:00 0.562 -0.260
1950-01-03 06:00:00 -0.200 0.240
1950-01-03 07:00:00 -0.226 0.202

现在,我想做一个“意大利面条图”,其中确定一种颜色的“意大利面条组”是曲线是 diff_1 还是 diff_2 (所以 x 轴是从 01-01 到 01-03 的时间, y 轴是差异,每个“意大利面条”是一年)。我试图定位这个问题:

Plot pandas data frame with year over year data

但是,我担心我的一维太多了。有什么想法可以实现吗?

编辑:下面的简单图片说明了我正在寻找的内容。一种颜色出现多条线是因为 x 轴上的时间段每年重复一次。

enter image description here

最佳答案

这是我能做的最好的事情,我并不完全满意,但可能已经足够好了:

# add a column with the year so you can pivot on it later.
tdf = df.assign(year=df.index.year)
# make all dates have the same year (a leap one just in case)
tdf.index = df.index.map(lambda x: x.replace(year=2004))
# pivot using years as columns and put them in the topmost level.
tdf = (tdf.pivot(columns='year').swaplevel(0, 1, axis='columns'))
print(tdf)

year 1949 1950 1949 1950
diff_1 diff_1 diff_2 diff_2
2004-01-01 06:00:00 -0.555 -0.654 -0.123 0.572
2004-01-01 07:00:00 -0.654 -0.544 0.230 0.092
2004-01-02 06:00:00 -0.879 0.374 0.012 -0.275
2004-01-02 07:00:00 -0.459 0.562 0.672 -0.260
2004-01-03 06:00:00 -0.588 -0.200 0.980 0.240
2004-01-03 07:00:00 -0.068 -0.226 0.375 0.202

# create a list of as many colors as columns in df
color = [c['color'] for c in plt.rcParams['axes.prop_cycle'][:df.columns.size]]
# plot
ax = plt.subplot()
for year in tdf.columns.levels[0]:
tdf[year].plot(color=color, legend=False, ax=ax)
plt.legend(ax.lines[:df.columns.size], df.columns, loc='best')
plt.show()

enter image description here

现在根据您的心意内容自定义刻度标签。

关于python - 具有重复序列的 Pandas 数据帧 : How to do a spaghetti plot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30978550/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com