Python 分组条形图 Pandas
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40420240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grouped Bar graph Pandas
提问by Shubham R
I have a table in a pandas DataFrame
named df
:
我在熊猫中有一张桌子,DataFrame
名为df
:
+--- -----+------------+-------------+----------+------------+-----------+
|avg_views| avg_orders | max_views |max_orders| min_views |min_orders |
+---------+------------+-------------+----------+------------+-----------+
| 23 | 123 | 135 | 500 | 3 | 1 |
+---------+------------+-------------+----------+------------+-----------+
What I am looking for now is to plot a grouped bar graph which shows me (avg, max, min) of views and orders in one single bar chart.
我现在正在寻找的是绘制一个分组条形图,它在一个条形图中向我显示(平均、最大、最小)视图和订单。
i.e on x axis there would be Views and orders separated by a distance and 3 bars of (avg, max, min) for views and similarly for orders.
即在 x 轴上,视图和订单将被分开的距离和 3 条(平均、最大值、最小值)用于视图和类似的订单。
I have attached a sample bar graph image, just to know how the bar graph should look.
我附上了一个示例条形图图像,只是为了了解条形图的外观。
Green color should be for avg, yellow for max and pink for avg.
I took the following code from setting spacing between grouped bar plots in matplotlibbut it is not working for me:
我从在 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)
plotting: [23, 135, 3] ... ValueError: shape mismatch: objects cannot be broadcast to a single shape
绘图:[23, 135, 3] ... ValueError:形状不匹配:对象不能广播到单个形状
回答by IanS
Using 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()
回答by Thomas G.
You should not have to modify your dataframe just to plot it in a certain way right ?
您不必为了以某种方式绘制它而修改您的数据框,对吗?
Use seaborn !
使用seaborn!
import seaborn as sns
sns.catplot(x = "x", # x variable name
y = "y", # y variable name
hue = "type", # elements in each group variable name
data = df, # dataframe to plot
kind = "bar")