如何在 Matplotlib 中獲取最後一個圖形的顏色?


要獲取最後一個圖形的顏色,我們可以對每個繪圖使用 get_color() 方法。

  • 設定圖形大小並調整子圖之間及周圍的間距。
  • 使用 numpy 建立 xy 資料點。
  • 使用 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

更新日期:2021 年 6 月 15 日

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.