gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:04:36 24 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/48500372/

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