这是我的代码:
import pandas as pd
data = {'bar_groups': ['A', 'A', 'B', 'C', 'B', 'A', 'C', 'B', 'C', 'B'],
'color_groups': [1, 2, 3, 4, 5, 6, 7, 8, 1, 2],
0: [0.258, 0.087, 0.168, 0.241, 0.182, 0.236, 0.231, 0.092, 0.283, 0.186],
1: [0.212, 0.208, 0.135, 0.24, 0.256, 0.27, 0.218, 0.151, 0.162, 0.18],
2: [0.009, 0.062, 0.031, 0.017, 0.027, 0.02, 0.043, 0.087, 0.011, 0.04],
3: [0.006, 0.015, 0.006, 0.009, 0.009, 0.01, 0.016, 0.006, 0.004, 0.011],
4: [0.002, 0.002, 0.002, 0.002, 0.007, 0.005, 0.18, 0.002, 0.025, 0.004],
5: [0.268, 0.269, 0.262, 0.278, 0.278, 0.269, 0.19, 0.229, 0.395, 0.234],
6: [0.004, 0.017, 0.008, 0.009, 0.018, 0.002, 0.005, 0.012, 0.002, 0.04],
7: [0.242, 0.338, 0.387, 0.204, 0.222, 0.188, 0.117, 0.422, 0.117, 0.306],
8: [0.006, 0.015, 0.006, 0.009, 0.009, 0.01, 0.016, 0.006, 0.004, 0.011]}
df = pd.DataFrame(data)
# Plot code
fig, ax = plt.subplots(figsize=(10,7))
# bars on the left
df_target = df.groupby(["bar_groups", "color_groups"]).size()
df_target = (df_target / df_target.groupby("bar_groups").transform(sum)).unstack(level='color_groups')
df_target.plot(kind='bar',stacked=True, position=1, colormap='Set3', width=0.4, ax=ax, edgecolor='grey')
# bars on the right
df_prob = df[['bar_groups', 0,1,2,3,4,5,6,7,8]].groupby('bar_groups').mean()
df_prob.plot.bar(stacked=True, ax=ax, position=0, cmap='Set3', width=0.4, legend=False, alpha=0.6, edgecolor='grey')
ax.set_xlim(-0.75,9)
ax.set_ylabel('Actual (left) & Predicted (right) bars')
plt.title('Grouped bar chart')
由于外部原因,我不得不删除最后一列(8
),现在颜色完全改变了- matplotlib似乎删除了序列中的随机颜色(粉红色,紫色)。
1条答案
按热度按时间kpbwa7wx1#
df_target
df_prob
cmap
不会将相同的颜色应用于两个绘图调用。color
参数。'Set3'
的颜色mpl.colormaps['Set3'](range(9)
从'Set3'
创建9种颜色的列表,'Set3'
对应于列名0, 1, 2, ..., 8
。cmap='Set3'
绘图