Pandas- stacked bar chart with independent/unrelated partitions of bars

纵然是瞬间 提交于 2019-12-13 19:56:31

问题


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.

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?

Thanks!


回答1:


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

Output:

   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))

Output:



来源:https://stackoverflow.com/questions/47824636/pandas-stacked-bar-chart-with-independent-unrelated-partitions-of-bars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!