首页 > 解决方案 > 让多个 matplotlib 轴使用相同的颜色循环器

问题描述

我想知道是否有一种简单的方法可以让 matplotlib 对子图中的所有轴使用相同的颜色循环,而不是在绘制到新轴时“重新启动”它。

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

标签: pythonmatplotlib

解决方案


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

推荐阅读