Grouped Bar graph Pandas

时间:2016-11-04 10:22:55

标签: python python-2.7 python-3.x pandas matplotlib

我在名为DataFrame的pandas 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 绿色应为平均值,黄色为最大值,粉红色为平均值。

我从setting spacing between grouped bar plots in 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:形状不匹配:无法将对象广播为单个形状

2 个答案:

答案 0 :(得分:13)

使用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 :(得分:5)

您不必只是为了以某种方式绘制数据框就可以修改数据框吗?

使用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")

source