我想更改堆叠条形图中的颜色,而不仅仅是预设颜色。我尝试了不同的方法,但我没有让它适用于我拥有的代码。我有这个代码:
import matplotlib.pyplot as plt
import numpy as np
species = (
"MP 1",
"MP 2",
"MP 3",
)
max_A2M4 = 2260
weight_counts = {
"Below": np.array([76, 100, 24]) / max_A2M4*100,
"Middle": np.array([1600-76, 1779-100, max_A2M4-24]) / max_A2M4*100,
"Above": np.array([max_A2M4-1600, max_A2M4-1779, 0]) / max_A2M4*100,
}
width = 0.5
fig, ax = plt.subplots()
bottom = np.zeros(3)
colors = ['lightgrey', 'gray', 'lightgrey']
for boolean, weight_count in weight_counts.items():
p = ax.bar(species, weight_count, width, label=boolean, bottom=bottom)
bottom += weight_count
ax.set_title("Window settings")
ax.legend(loc="upper right")
ax.set_ylim(-5,105)
plt.show()
我使用的模板来自:https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_stacked.html
我希望蓝色和绿色条的颜色为浅灰色,橙色条的颜色为灰色。
我尝试了不同的循环,但没有任何效果。
我感谢所有帮助!
您可以将颜色作为参数传递给
ax.bar
。
for (boolean, weight_count), c in zip(weight_counts.items(), colors):
p = ax.bar(species, weight_count, width, label=boolean, bottom=bottom, color=c)