大熊猫在图表上显示多个条形图

时间:2015-07-08 21:28:06

标签: python pandas matplotlib

我的数据如下:

term    date    change1 change2
aaa  2010-03-01   23.00   24.31
bbb  2010-03-01   25.00   0.00
ccc  2012-05-01   100.00  100.00

日期列可以包含重复日期。我想为每个术语绘制,即change1和change2是什么。我想把这个术语作为x轴,并且change1和change2共享相同的y轴,但是并排绘制成条形图。 我知道如何做y轴部分,但不知道如何设置x轴。我也希望每个术语以某种方式显示日期,如果可能的话,否则这不是优先事项。

以下是我所拥有的:

fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
df.change1.plot(kind = 'bar', color = 'red', ax = ax , position = 1)
df.change2.plot(kind = 'bar', color = 'blue', ax = ax2, position = 2)
ax.set_ylabel= ('change1')
ax2.set_ylabel=('change2')
plt.show()

谢谢,

1 个答案:

答案 0 :(得分:4)

x-axis上的标签设为term的一种方法是将term设置为索引:

df = df.set_index(['term'])

例如,

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'change1': [23.0, 25.0, 100.0],
 'change2': [24.309999999999999, 0.0, 100.0],
 'date': ['2010-03-01', '2010-03-01', '2012-05-01'],
 'term': ['aaa', 'bbb', 'ccc']})
df = df.set_index(['term'])
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()

df['change1'].plot(kind='bar', color='red', ax=ax, position=0, width=0.25)
df['change2'].plot(kind='bar', color='blue', ax=ax2, position=1, width=0.25)
ax.set_ylabel = ('change1')
ax2.set_ylabel = ('change2')
plt.show()

enter image description here

或者,您可以明确地设置xticklabels:

,而不是设置索引
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'change1': [23.0, 25.0, 100.0],
 'change2': [24.309999999999999, 0.0, 100.0],
 'date': ['2010-03-01', '2010-03-01', '2012-05-01'],
 'term': ['aaa', 'bbb', 'ccc']})

fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()


df['change1'].plot(kind='bar', color='red', ax=ax, position=0, width=0.25)
df['change2'].plot(kind='bar', color='blue', ax=ax2, position=1, width=0.25)
ax.set_ylabel = 'change1'
ax2.set_ylabel = 'change2'
labels = ['{}\n{}'.format(date, term) for date, term in zip(df['date'], df['term'])]
ax.set_xticklabels(labels, minor=False)
fig.autofmt_xdate()

plt.show()

enter image description here

根据评论中的问题, 要为每个date创建一个新的图,您可以迭代这些组 df.groupby(['date'])

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'change1': [23.0, 25.0, 100.0],
 'change2': [24.309999999999999, 0.0, 100.0],
 'date': ['2010-03-01', '2010-03-01', '2012-05-01'],
 'term': ['aaa', 'bbb', 'ccc']})

groups = df.groupby(['date'])
fig, axs = plt.subplots(nrows=groups.ngroups)
for groupi, ax in zip(groups,axs):
    index, grp = groupi
    ax2 = ax.twinx()
    grp['change1'].plot(kind='bar', color='red', ax=ax, position=0, width=0.25)
    grp['change2'].plot(kind='bar', color='blue', ax=ax2, position=1, width=0.25)
    ax.set_ylabel = 'change1'
    ax2.set_ylabel = 'change2'
    ax.set_title(index)
    ax.set_xticklabels(grp['term'].tolist(), minor=False, rotation=0)
fig.tight_layout()
plt.show()

enter image description here