Getting multiple matplotlib axes to use the same color cycler

Viewed 219

I'm wondering if there's a straightforward way to have matplotlib use the same color cycle for all axes in a subplot, rather than 'restarting' it when I plot to a new axis.

MWE:

import matplotlib
import numpy as np

matplotlib.rcParams['axes.prop_cycle'] = matplotlib.cycler(
        color=['red', 'blue', 'black']
        )

X = np.linspace(0, 100, 100)

fig, (ax1, ax2) = matplotlib.pyplot.subplots(nrows=2)
ax1.plot(X, 1.5*X)  # plots red line
ax1.plot(X, 0.9*X)  # plots blue line
ax2.plot(X, X)  # plots red line again, rather than black line
1 Answers

As a prerequisite, the first color is used sequentially in other graphs. If you want to draw in your own color, use C2, just as you would use the defaults from C0 to C9. You can also make a list of your own colors and use them. See here.

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['axes.prop_cycle'] = plt.cycler(
        color=['red', 'blue', 'black']
        )

X = np.linspace(0, 100, 100)

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(X, 1.5*X)  # plots red line
ax1.plot(X, 0.9*X)  # plots blue line

ax2.plot(X, X, color='C{}'.format(2))  # plots red line again, rather than black line

plt.show()

enter image description here

Put another way.

cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
ax2.plot(X, X, color= cycle[2])
Related