如何在Matplotlib中更改图例字体?
要在Matplotlib中更改图例字体,我们可以按照以下步骤执行 –
- 设置图形大小并调整子图周围和之间的填充。
-
使用numpy创建x数据点。
-
使用plot()方法绘制x、sin(x)和cos(x)。
-
使用legend()方法放置图例。
-
迭代legend.get_texts()并更新图例字体。
-
使用show()方法显示图形。
示例
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()