Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách lấy màu của figure cuối cùng trong Matplotlib?

Để lấy màu của figure cuối cùng, ta dùng get_color() cho từng plot.

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
  • Tạo điểm x, y bằng numpy.
  • Vẽ (x, x), (x, x2), (x, x3) bằng plot().
  • Đặt legend cho từng đường.
  • Lấy màu từng plot bằng get_color().
  • Hiển thị hình bằng show().

Ví dụ

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

Kết quả

Cách lấy màu của figure cuối cùng trong Matplotlib?

Kèm theo biểu đồ, console in ra:

Color of the first plot: #1f77b4
Color of the second plot: #ff7f0e
Color of the third plot: #2ca02c