分组柱状图Pandas

30

我在pandas的DataFrame中有一张名为df的表:


Translated Text:

我在pandas的DataFrame中有一张名为df的表:

+--- -----+------------+-------------+----------+------------+-----------+
|avg_views| avg_orders | max_views   |max_orders| min_views  |min_orders |
+---------+------------+-------------+----------+------------+-----------+
| 23       | 123       |   135       | 500      |    3       |    1      |
+---------+------------+-------------+----------+------------+-----------+ 

我现在想要绘制一张分组条形图,它可以在一个图表中显示出浏览量和订单的平均值、最大值和最小值。

例如,x轴上会有浏览量和订单,它们之间会有一定距离,并且分别有3种颜色的条形图表示(平均值、最大值、最小值)。

我附上了一张样本条形图图片,仅供参考。

just sample: green color should be for avg, yellow for max and pin 绿色应该代表平均值,黄色代表最大值,粉色代表最小值。

我从设置matplotlib中分组条形图之间的间距中获取了以下代码,但对我不起作用:

plt.figure(figsize=(13, 7), dpi=300)

groups = [[23, 135, 3], [123, 500, 1]]
group_labels = ['views', 'orders']
num_items = len(group_labels)
ind = np.arange(num_items)
margin = 0.05
width = (1. - 2. * margin) / num_items

s = plt.subplot(1, 1, 1)
for num, vals in enumerate(groups):
    print 'plotting: ', vals
    # The position of the xdata must be calculated for each of the two data 
    # series.
    xdata = ind + margin + (num * width)
    # Removing the "align=center" feature will left align graphs, which is 
    # what this method of calculating positions assumes.
    gene_rects = plt.bar(xdata, vals, width)
s.set_xticks(ind + 0.5)
s.set_xticklabels(group_labels)

绘图: [23, 135, 3] ... ValueError: 形状不匹配:无法将对象广播到单个形状


你能提供一个 [MCVE] 吗? - IanS
@IanS,请检查,我已经附加了代码。 - Shubham R
它为什么不工作?有错误信息吗? - IanS
2个回答

38
使用pandas:
import pandas as pd

groups = [[23,135,3], [123,500,1]]
group_labels = ['views', 'orders']

# Convert data to pandas DataFrame.
df = pd.DataFrame(groups, index=group_labels).T

# Plot.
pd.concat(
    [
        df.mean().rename('average'), 
        df.min().rename('min'), 
        df.max().rename('max')
    ],
    axis=1,
).plot.bar()

Result plot


1
运行得非常好!只有一个问题,这只给了我条形图,是否有办法将每个条的值实际放在其顶部?比如对于最大订单,我能否在其上方标注其值? - Shubham R
很抱歉,我不知道如何去做。或许可以尝试 这个回答…… - IanS
或者直接从文档中查看autolabel - IanS

34

你不应该修改你的数据帧来以某种特定方式绘制,对吗?

使用 seaborn!

import seaborn as sns

sns.catplot(
    x="x",       # x variable name
    y="y",       # y variable name
    hue="type",  # group variable name
    data=df,     # dataframe to plot
    kind="bar",
)

来源


如果你想知道如何改变 sns.catplotfigsize,可以使用 height 关键字来控制大小,使用 aspect 关键字来控制形状。来源 - Ray Walker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接