# Matplotlib 中的颜色循环

Salman Mehmood 2024年2月15日

## 在 Matplotlib 中使用颜色循环获取和设置颜色属性

Matplotlib 1.5 及更高版本已更改为使用 `Cycler` 库。我们可以使用名为 `prop_cycler` 的迭代来代替 `color_cycle`、属性的 `dict`，或者在我们的程序中仅使用颜色。

``````next_color = next(color_cycle)
``````

`next_color` 指定我们要在绘图中显示的下一种颜色。按照设计，如果不更改迭代器，我们将无法获得它的状态。

``````import numpy as np
import matplotlib.pyplot as plot

def custom_plot(x, y, **kwargs):
ax = kwargs.pop("ax", plot.gca())
(base_line,) = ax.plot(x, y, **kwargs)
ax.fill_between(x, 0.9 * y, 1.1 * y, facecolor=base_line.get_color(), alpha=0.5)

x = np.linspace(0, 1, 10)
custom_plot(x, x)
custom_plot(x, x * 2)
custom_plot(x, x - x, color="yellow", lw=3)
plot.show()
``````

``````import numpy as np
import matplotlib.pyplot as plot
import matplotlib as mpl

# Takes key value pair to set default cycle color
mpl.rcParams["axes.prop_cycle"] = mpl.cycler(color=["b", "r", "r"])

x1 = np.linspace(0, 20, 100)

fig, axes = plot.subplots(nrows=2)

for i in range(10):
axes[0].plot(x1, i * (x1 * 10) ** 2)  # create a plot on zero axis

for j in range(10):
axes[1].plot(x1, j * np.cos(x1))  # # create second plot on 1 axis

plot.show()
``````

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.