如何在 Matplotlib 中获取最后一个图形的颜色?
要获取最后一个图形的颜色,我们可以对每个绘图使用 get_color() 方法。
- 设置图形大小并调整子图之间及周围的间距。
- 使用 numpy 创建 x 和 y 数据点。
- 使用 plot() 方法绘制 (x, x), (x, x2) 和 (x, x3)。
- 为每条绘图线放置图例。
- 使用 get_color() 方法获取每个绘图的颜色。
- 要显示图形,请使用 show() 方法。
示例
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(10)
y = np.arange(10)
p = plt.plot(x, y, x, y ** 2, x, y ** 3)
plt.legend([p[0], p[1], p[2]], ["$y=x$", "$y=x^2$", "$y=x^3$"])
print("Color of the first plot: ", p[0].get_color())
print("Color of the second plot: ", p[1].get_color())
print("Color of the third plot: ", p[2].get_color())
plt.show()输出

除了绘图外,你还会在控制台上看到以下输出 -
Color of the first plot: #1f77b4 Color of the second plot: #ff7f0e Color of the third plot: #2ca02c
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP