Để thay đổi font chữ legend trong matplotlib, ta thực hiện:
- Thiết lập kích thước hình và điều chỉnh khoảng đệm giữa và xung quanh subplots.
- Tạo x dùng numpy.
- Vẽ x, sin(x), cos(x) dùng plot().
- Dùng legend() đặt legend.
- Lặp legend.get_texts() cập nhật font chữ legend.
- Hiển thị hình dùng show().
Ví dụ
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
plt.plot(x, np.sin(x), label="$y=sin(x)$")
plt.plot(x, np.cos(x), label="$y=cos(x)$")
legend = plt.legend(loc='upper right')
i = 1
for t in legend.get_texts():
t.set_text("name %d" % i)
i += 1
plt.show()
Kết quả
