matplotlib stackplot: how to assign specific color

Viewed 62

I am making a grid of multiple matplotlib stackplots. As-is the colors are assigned randomly to each area/group, which means they are not consistent across the plots. An example:

a = [1, 3, 5]
b = [3, 4, 5]
c = [4, 5, 6]
d = [6, 7, 8]
x = [0, 1, 2]

fig, axs = plt.subplots(1, 2, figsize=(20, 7), sharex=True, sharey=True)
axs[0].stackplot(x, a, b, c, labels=['a', 'b', 'c'])
axs[1].stackplot(x, c, d, labels=['c', 'd'])
axs[0].legend()
axs[1].legend()
plt.show()

By default matplotlib uses inconsistent colors

As you can see, in the first subplot c is green, in the second it is blue. In the first plot orange means group b, in the second plot it means group d.

My question

How can I make matplotlib assign a specific color to each group, that is consistent across all subplots. Solution must work for many more than 2 subplots. Thanks!

Note: I have seen questions on stackoverflow that ask how to set colors on a stackplot, but all of them use colormaps that indeed change the color, but does not necessarily make it consistent across plots. (Unless I misunderstood?)

1 Answers

You can create dict base labels and colors and then use them for plotting with constant color for each label in different plots.

import matplotlib.pyplot as plt

a = [1, 3, 5]
b = [3, 4, 5]
c = [4, 5, 6]
d = [6, 7, 8]
x = [0, 1, 2]


dct_color = {'a':'blue', 'b':'green', 'c':'red', 'd':'yellow'}

fig, axs = plt.subplots(1, 2, figsize=(20, 7), sharex=True, sharey=True)
axs[0].stackplot(x, a, b, c, labels=['a', 'b', 'c'], 
                 colors = [dct_color.get(l, '#9b59b6') for l in ['a', 'b', 'c']])
axs[1].stackplot(x, c, d, labels=['c', 'd'], 
                 colors = [dct_color.get(l, '#9b59b6') for l in ['c', 'd']])
axs[0].legend()
axs[1].legend()
plt.show()

enter image description here

Related