pythonmatplotlibcolorsstacked-bar-chart

How do I change the colors of the bars in a stacked bar chart?


I want to change to colors in my stacked bar chart, and not only have the preset colors. I have tried different ways, but I do not get it to work for the code I have. I have this code:

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

which gives me this plot: (https://i.sstatic.net/BS3PH.png)](https://i.sstatic.net/BS3PH.png)

I'm using the template from: https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_stacked.html

I want the blue and green bars to have the color lightgray, and the orange bars to be gray.

I have tried different loops but nothing works.

I'm thankful for all help!


Solution

  • You can pass the color as a parameter to 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)