matplotlib 为堆叠条形图的每个组件给予自定义颜色

nwlls2ji  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(163)

我想为堆叠条形图的每个组件给予自定义颜色。

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列的堆叠条形图的每个组成部分给予自定义颜色。列2示出列1的分解,列3示出列2的绿色组分的分解。

cu6pst1q

cu6pst1q1#

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

相关问题