如何在 Matplotlib 中横向显示图例元素?
要横向显示图例元素,我们可以采取以下步骤
- 设置图形大小并调整子图之间和周围的内边距。
- 使用 plot() 方法,绘制带有标签 line1、line2 和 line3 的线条。
- 使用 legend() 方法在图形中放置图例,参数中 ncol 值表示标签的数量。
- 要显示图形,请使用 show() 方法。
示例
from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True line1, = plt.plot([1, 2, 3], label="line1") line2, = plt.plot([3, 2, 1], label="line2") line3, = plt.plot([2, 3, 1], label="line3") plt.legend(ncol=3, loc="upper right") plt.show()
输出
广告