如何将图例置于情节之外

新手上路,请多包涵

我有一系列 20 个图(不是子图)要在一个图中制作。我希望传说在盒子外面。同时,我不想更改轴,因为图形的大小会减小。

  1. 我想将图例框保留在绘图区域之外(我希望图例位于绘图区域的右侧之外)。
  2. 有没有办法减小图例框内文本的字体大小,使图例框的大小变小?

原文由 pottigopi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 639
2 个回答
  import matplotlib.pyplot as plt
  from matplotlib.font_manager import FontProperties

  fontP = FontProperties()
  fontP.set_size('xx-small')

  p1, = plt.plot([1, 2, 3], label='Line 1')
  p2, = plt.plot([3, 2, 1], label='Line 2')
  plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', prop=fontP)

在此处输入图像描述

  • fontsize='xx-small' 也可以,无需导入 FontProperties
   plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='xx-small')

原文由 Navi 发布,翻译遵循 CC BY-SA 4.0 许可协议

有很多方法可以做你想做的事。要添加到 Christian AlisNavi 已经说过 的内容,您可以使用 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() ,则省略 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 图例指南。您也可以看看 plt.figlegend()

原文由 Joe Kington 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题