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

Cách tô màu diện tích dưới đường bậc thang (step curve) trong Matplotlib


Dùng fill_between() với tham số step="pre" để tô màu dưới đường bậc thang (step curve).

  • Tạo dữ liệu x, y1, y2.
  • Gọi fill_between(x, y1, step="pre", alpha=0.4).
  • Vẽ đường step bằng plot(x, y, drawstyle="steps").

Ví dụ minh họa

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.fill_between(x, y1, step="pre", alpha=0.4)
plt.fill_between(x, y2, step="pre", alpha=0.4)
plt.plot(x, y1, drawstyle="steps")
plt.plot(x, y2, drawstyle="steps")
plt.show()

Kết quả đầu ra

Cách tô màu diện tích dưới đường bậc thang (step curve) trong Matplotlib