gpt4 book ai didi

python - 如何将图例置于情节之外

转载 作者:IT老高 更新时间:2023-10-28 11:59:06 26 4
gpt4 key购买 nike

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

  1. 我想将图例框保留在绘图区域之外(我希望图例在绘图区域的右侧之外)。
  2. 有什么办法可以减小图例框内文字的字体大小,让图例框的尺寸变小?

最佳答案

有很多方法可以做你想做的事。添加到 what Christian AlisNavi already said ,您可以使用 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()

alt text

如果我们做同样的事情,但使用 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()

Alt text

同样,使图例更加水平和/或将其放在图形的顶部(我还打开了圆角和一个简单的阴影):

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()

alt text

或者,缩小当前绘图的宽度,并将图例完全放在图形轴之外(注意:如果您使用 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()

Alt text

并以类似的方式,将绘图垂直缩小,并在底部放置一个水平图例:

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()

Alt text

看看matplotlib legend guide .你也可以看看 plt.figlegend() .

关于python - 如何将图例置于情节之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4700614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com