如何在 pandas 中创建叠加条形图 [英] How to create overlay bar plot in pandas

查看:87
本文介绍了如何在 pandas 中创建叠加条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在更新一些较早的代码以使用pandas.DataFrame时,我陷入了以下问题...

While updating some of my earlier code to use pandas.DataFrame, I'm got stuck with following problem...

这是我的原始代码将创建的参考图:

This is the reference plot that my original code would create:

import pandas as pd
import matplotlib.pyplot as plt

a = range(1, 25)
b = a
c = [x+2 for x in b]
d = [x*2 for x in c]

plt.bar(a, d)
plt.bar(a, c)
plt.bar(a, b)
plt.show()

问题定义:

我想使用内置功能pandas.DataFrame创建这个非常相似的情节.确切地说,只有条形图的位置是相关的,我对轴刻度的格式/标签不感兴趣.

I would like to create this very same plot using pandas.DataFrame built in functionality. To be precise, only the bars placement is relevant, I'm not interested in the formatting/labeling of axis ticks.

df = pd.DataFrame({'a': a, 'b': b, 'c': c, 'd': d}, columns=['a', 'b', 'c', 'd'])
df.set_index('a', inplace=True)

df.plot.bar()
plt.show()

默认的熊猫条形图(如上所示)或添加stacked=True选项(见下文)均未产生预期的结果.

Neither, default pandas bar-plot (shown above) nor adding stacked=True option (see below), produced the desired result.

df.plot.bar(stacked=True)
plt.show()

很遗憾,overlay=True选项不存在.

还有另一种(最好是优雅的)方式来达到预期的效果吗?

Is there another (preferably elegant) way to achieve the desired result?

如果没有其他可用的内容,我将只修改pandas.DataFrame值(即相互减去各列),然后使用stacked=True选项.在实现之前,我很期待看到您的建议...

If nothing else is available, I will just modify the pandas.DataFrame values (i.e. subtract the columns from each other) and then use stacked=True option. Before, I implement that, I'm looking forward to see your suggestions...

推荐答案

您可以将ax参数设置为

You can set the ax parameter with the value returned by subplots, like this:

_, ax = plt.subplots()
df.d.plot(kind='bar', ax=ax, color='red')
df.c.plot(kind='bar', ax=ax, color='green')
df.b.plot(kind='bar', ax=ax, color='blue')

这篇关于如何在 pandas 中创建叠加条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆