如何在 Matplotlib 中的图例中显示文本标签?
matplotlibpythondata visualization
要仅在图例中显示文本标签,我们可以使用 legend 方法,参数中带有 handlelength=0、handletextpad=0 和 fancybox=0。
步骤
设置图形大小并调整子图之间和周围的填充。
使用 numpy 创建随机 x 和 y 数据点。
使用 subplots() 方法创建一个图形和一组子图。
使用 plot() 方法绘制 x 和 y 数据点,标签为"Zig-Zag"用于图例。
使用 legend() 方法放置绘图标签,参数为 handlelength=0、handletextpad=0 和 fancybox=0。
要显示图形,请使用 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.random.rand(100) y = np.random.rand(100) fig, ax = plt.subplots() ax.plot(x, y, label='Zig-Zag', c="red") ax.legend(loc="upper right", handlelength=0, handletextpad=0, fancybox=True) plt.show()