如何在 Matplotlib 中更改图例字体名称?

matplotlibpythondata visualization更新于 2025/6/8 3:56:17

要更改 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()

输出


相关文章


有用资源