Pandas-堆叠的条形图,具有独立/不相关的条形分区 [英] Pandas- stacked bar chart with independent/unrelated partitions of bars

查看:77
本文介绍了Pandas-堆叠的条形图,具有独立/不相关的条形分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个堆叠的条形图,条形图的分区彼此独立.例如,假设我有2个盒子. (计算数字...)框1包含3个红色,5个蓝色和8个黄色的球.方框2有2个橙色,6个绿色,9个紫色和10个黑色的球.

I would like to create a stacked bar chart, where the partitions of the bars are independent from another. For example, let's say I have 2 boxes of balls. (Making up numbers...) Box 1 has 3 red, 5 blue, and 8 yellow balls. Box 2 has 2 orange, 6 green, 9 purple, and 10 black balls.

现在,我想创建一个堆叠的条形图,其中每个框都带有一个条形图,并且在每个条形图中,我可以显示特定颜色的球数.球的颜色因包装盒而异,所以我想在条形图中标记这些分组.

Now, I would like to create a stacked bar chart with a bar for each box, and within each bar, I can show the number of balls for a particular color. The colors of the balls are different depending on the box, so I would want to label these groupings within the bars.

在我的特定情况下,我有5个垃圾箱,每个垃圾箱内有8-12个(不同的)分组.

In my particular case, I have 5 bins, and within each bin, there are between 8-12 (different) groupings.

这似乎不是最好的图表类型,那么您有没有建议的其他图表类型?

This may not seem like the best type of chart, so do you have another chart/plot type that you would recommend?

谢谢!

推荐答案

好的,让我们尝试下面的代码:

Sure, let's try this code:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'box':[1]*3+[2]*4,'color':['red','blue','yellow','orange','green','purple','black'],
                  'Value':[3,5,8,2,6,9,10]})
df

输出:

   Value  box   color
0      3    1     red
1      5    1    blue
2      8    1  yellow
3      2    2  orange
4      6    2   green
5      9    2  purple
6     10    2   black

现在,让我们重塑和绘制:

Now, let's reshape and plot:

df.set_index(['box','color']).unstack()['Value']\
  .plot(kind='bar', stacked=True, color=df.color.sort_values().tolist(), figsize=(15,8))

输出:

这篇关于Pandas-堆叠的条形图,具有独立/不相关的条形分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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