问题
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