Search code examples
pythonmatplotlibstacked-bar-chart

Give custom color to each component of stacked bar plot


I would like to give custom color to each component of the stacked bar plot.

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

bar plot example

I would like to give custom colors to each component of the stacked barplot in column 2 and column 3. Column 2 is showing the breakdown of column 1, and column 3 is showing the breakdown of the green component of column 2.


Solution

  • ax.patches contains a list of the Rectangles that are used to draw the bar plot, in the order of their creation. So there are 3 "seagreen" rectangles, 3 "gray" rectangles, and 3 "orange" rectangles.

    If you define a list of the colors you want (must match the number of rectangles, including zero-height rectangles), then you could iterate over the list of patches and set their colors

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

    enter image description here