Matplotlib:如何调整图例标记和标签之间的空间?

rht*_*ica 15 python matplotlib legend

我想调整图例标记和标签之间的空间.有时候这个空间太大了.有谁知道如何做到这一点?

谢谢.

tmd*_*son 20

legend()有一个叫做的kwarg handletextpad,可以做你想要的.默认情况下,此值设置为0.8.来自文档:

handletextpad :float或None

图例句柄和文本之间的垫.以字体大小单位测量.

默认值为None,它将从中获取值 legend.handletextpad rcParam.

所以当你打电话时legend,添加那个kwarg,然后试验这个值.就像是:

ax.legend(handletextpad=0.1)
Run Code Online (Sandbox Code Playgroud)

考虑以下:

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2)

ax1.plot(range(5), 'ro', label='handletextpad=0.8')
ax2.plot(range(5), 'bo', label='handletextpad=0.1')

ax1.legend()
ax2.legend(handletextpad=0.1)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述