matplotlib 设置legend的位置在轴最上方,长度与图的长度相同

import matplotlib.pyplot as plt
import numpy as np

x1 = np.linspace(0, 10, 50)
x2 = [6,4,3]

ax = plt.subplot()
ax.plot(x1, label="test1")
ax.plot(x2, label="test2")
# 设置图例的位置
# 将左下角放置在【0, 1.02】位置处,横为1,纵为0.102
# borderaxespad:设置坐标轴与图例外边框的间距
ax.legend(bbox_to_anchor=(0, 1.02, 1, 0.102), 
loc='lower left',ncol=2, mode="expand", borderaxespad=0)

plt.show()

matplotlib 设置legend的位置在轴最上方,长度与图的长度相同_第1张图片
参考文献:

  • https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html

你可能感兴趣的:(Python,matplotlib)