连接两个Pandas数据帧并生成并排条形图?

2024-04-26 10:08:04 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个Pandas数据帧,df1和{},每个都有两列,hour和{}。两个数据帧中缺少一些小时。在

import pandas as pd
import matplotlib.pyplot as plt
data1 = [
    ('hour', [0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12,
              13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]),
    ('value', [12.044324085714285, 8.284134466666668, 9.663580800000002,
               18.64010145714286, 15.817029916666664, 13.242198508695651,
               10.157177889201877, 9.107153674476985, 10.01193336545455,
               16.03340384878049, 16.037368506666674, 16.036160044827593,
               15.061596637500001, 15.62831551764706, 16.146087032608694,
               16.696574719512192, 16.02603831463415, 17.07469460470588,
               14.69635686969697, 16.528905725581396, 12.910250661111112,
               13.875522341935481, 12.402971938461539])
    ]

df1 = pd.DataFrame.from_items(data1)
df1.head()
#    hour      value
# 0     0  12.044324
# 1     1   8.284134
# 2     2   9.663581
# 3     4  18.640101
# 4     5  15.817030

data2 = [
    ('hour', [0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
              15, 16, 17, 18, 19, 20, 21, 22, 23]),
    ('value', [27.2011904, 31.145661266666668, 27.735570511111113,
               18.824297487999996, 17.861847334275623, 25.3033003254902,
               22.855934450000003, 31.160574200000003, 29.080220000000004,
               30.987719745454548, 26.431310216666663, 30.292641480000004,
               27.852885586666666, 30.682682472727276, 29.43023531764706,
               24.621718962500005, 33.92878745, 26.873105866666666,
               34.06412232, 32.696606333333335])
    ]

df2 = pd.DataFrame.from_items(data2)
df2.head()
#    hour      value
# 0     0  27.201190
# 1     5  31.145661
# 2     6  27.735571
# 3     7  18.824297
# 4     8  17.861847

我想使用hour键将它们连接在一起,然后生成数据的并排条形图。x轴是hour,而{}将是value。在

我可以一次创建一个数据帧的条形图。在

^{pr2}$

enter image description here

_ = plt.bar(df2.hour.tolist(), df2.value.tolist())
_ = plt.xticks(df2.hour, rotation=0)
_ = plt.grid()
_ = plt.show()

enter image description here

但是,我想创建一个并列的条形图,如下所示:

enter image description here

谢谢你的帮助。在


Tags: 数据fromimportdataframevalueasitemsplt
2条回答

如果你愿意的话,你可以在一条线上完成。利用pandas plotting包装器,以及用多个列绘制数据帧将对绘图进行分组的事实。给定问题中df1df2的定义,可以调用

pd.merge(df1,df2, how='outer', on=['hour']).set_index("hour").plot.bar()
plt.show()

导致

enter image description here

请注意,在本例中,这省略了数字3,因为它不是两个数据帧中任何一个小时列的一部分。要包含它,请使用reset_index

^{pr2}$

enter image description here

首先对数据帧重新编制索引,然后使用数据创建两个条形图。矩形的位置由(x - width/2, x + width/2, bottom, bottom + height)给出。在

import numpy as np

index = np.arange(0, 24)
bar_width = 0.3

df1 = df1.set_index('hour').reindex(index)
df2 = df2.set_index('hour').reindex(index)

plt.figure(figsize=(10, 5))
plt.bar(index - bar_width / 2, df1.value, bar_width, label='df1')
plt.bar(index + bar_width / 2, df2.value, bar_width, label='df2')
plt.xticks(index)
plt.legend()

plt.tight_layout()
plt.show()

plot

相关问题 更多 >