有很多种方法可以做你想做的事。要添加到什么克里斯蒂安·阿里斯 https://stackoverflow.com/questions/4700614/how-to-put-the-legend-outside-the-plot/4700762#4700762 and 纳维已经说过了 https://stackoverflow.com/questions/4700614/how-to-put-the-legend-outside-the-plot/4700674#4700674,您可以使用bbox_to_anchor
关键字参数将图例部分放置在轴之外和/或减小字体大小。
在考虑减小字体大小(这会使内容变得非常难以阅读)之前,请尝试将图例放置在不同的位置:
那么,让我们从一个通用示例开始:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
ax.plot(x, i * x, label='$y = %ix$' % i)
ax.legend()
plt.show()
如果我们做同样的事情,但使用bbox_to_anchor
关键字参数我们可以将图例稍微移到轴边界之外:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
ax.plot(x, i * x, label='$y = %ix$' % i)
ax.legend(bbox_to_anchor=(1.1, 1.05))
plt.show()
同样,使图例更加水平和/或将其放在图的顶部(我还打开圆角和简单的阴影):
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
line, = ax.plot(x, i * x, label='$y = %ix$'%i)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
ncol=3, fancybox=True, shadow=True)
plt.show()
或者,缩小当前图的宽度,并将图例完全放在图的轴之外(注意:如果您使用tight_layout() https://matplotlib.org/3.2.1/tutorials/intermediate/tight_layout_guide.html,然后省略ax.set_position()
:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
ax.plot(x, i * x, label='$y = %ix$'%i)
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
# Put a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
以类似的方式,垂直缩小绘图,并在底部放置水平图例:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
line, = ax.plot(x, i * x, label='$y = %ix$'%i)
# Shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
box.width, box.height * 0.9])
# Put a legend below current axis
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=5)
plt.show()
看看matplotlib 图例指南 http://matplotlib.org/users/legend_guide.html#legend-location。您也可以看看plt.figlegend() http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.figlegend.