【问题标题】:Pandas data frame with repeating sequences: How to do a spaghetti plot?具有重复序列的 Pandas 数据框:如何绘制意大利面条图?
【发布时间】:2015-09-07 19:43:33
【问题描述】:

我得到的数据类似于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 轴上的时间段每年重复。

【问题讨论】:

  • 您能举个例子说明您要完成的工作吗?如果它是关于绘图的,也许可以在油漆中绘制一些东西,或者如果你试图将你的数据框转换为易于绘制的东西,则可以绘制一个示例数据框。
  • 两者皆有。结果应该看起来像链接问题中的图,只是在我的例子中,“diff_1”/“diff_2”出现在图例中,并且一种颜色的图表不止一张(代表年份)。我添加了一个非常简单的图形来说明我想要什么。

标签: python pandas plot time-series


【解决方案1】:

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

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

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

【讨论】:

  • 好吧,确实,这似乎是一项艰巨的任务,但显然它确实有效! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-04-15
  • 2021-01-26
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多