Để vẽ với thang đo khác nhau trong matplotlib (dual y-axis):
Các bước
- Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
- Tạo t, data1, data2 bằng numpy.
- Tạo figure và subplots ax1.
- Khởi tạo biến màu.
- Đặt nhãn trục x, y cho axis 1.
- Vẽ t, data1 bằng plot().
- Đặt màu nhãn tick bằng tick_params().
- Tạo axes song sinh chia sẻ trục X, ax2.
- Lặp lại bước 4, 6, 7 với dữ liệu khác trên axis 2.
- 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
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)
fig, ax1 = plt.subplots()
color = 'red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color = 'blue'
ax2.set_ylabel('sin', color=color)
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)
plt.show()
Kết quả
