# Matplotlib 中的顏色迴圈

Salman Mehmood 2022年5月11日

## 在 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.