我想为堆叠条形图的每个组件赋予自定义颜色。例如,在下面的条形图中:
import numpy as np
import matplotlib.pyplot as plt
labels = ['Cars', 'Electric/\nHybrid/\nFuel', 'Diesel/\nOctane/\nPremium']
row1 = [2000,1800,1200]
row2 = [0,110,280]
row3 = [0,90,320]
width = 0.35
fig, ax = plt.subplots()
ax.bar(labels, row1, width, color='seagreen')
ax.bar(labels, row2, width, bottom=row1, color='gray')
ax.bar(labels, row3, width, bottom=np.array(row2)+np.array(row1), color='orange')
ax.set_ylim(0,2200)
plt.show()
我想为第2列和第3列中的堆叠barplot的每个组件提供自定义颜色,第2列显示了第1列的细分,第3列显示了第2列的绿色组件的细分。
ax.patches
包含用于创建条形图的矩形的列表,按其创建顺序。因此,有3个“海绿色”矩形,3个“灰色”矩形和3个“橙色”矩形。
如果定义了所需颜色的列表(必须匹配矩形的数量,包括零高度的矩形),则可以遍历色块列表并设置其颜色
import numpy as np
import matplotlib.pyplot as plt
labels = ['Cars', 'Electric/\nHybrid/\nFuel', 'Diesel/\nOctane/\nPremium']
row1 = [2000,1800,1200]
row2 = [0,110,280]
row3 = [0,90,320]
colors = ['seagreen','red','orange','seagreen','purple','yellow','seagreen','blue','brown']
width = 0.35
fig, ax = plt.subplots()
ax.bar(labels, row1, width, color='seagreen')
ax.bar(labels, row2, width, bottom=row1, color='gray')
ax.bar(labels, row3, width, bottom=np.array(row2)+np.array(row1), color='orange')
ax.set_ylim(0,2200)
for p,color in zip(ax.patches,colors):
p.set_facecolor(color)
plt.show()