python绘制多个条形图_python-熊猫在图表上显示多个条形图

本文介绍了如何使用pandas DataFrame操作和matplotlib库创建条形图,展示如何根据'term'或'date'对数据进行条件划分,并展示了两种方法:设置索引和显式设置xticklabels。通过groupby函数,实现了按日期分组绘制不同图例的多图展示。
摘要由CSDN通过智能技术生成

使沿x轴的标签成为条件的一种方法是将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()

或者,您可以显式设置xticklabel而不是设置索引:

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

根据评论中的问题,

要为每个日期创建一个新图,您可以遍历

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值