您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-如何将图例排除在情节之外

Python-如何将图例排除在情节之外

有很多方法可以做你想要的。要添加@inalis@Navi所说的内容,可以使用b@R_371_2419@_to_anchor关键字参数将图例部分地放置在轴外and/or 减小字体大小。

在考虑减小字体大小(这会使阅读起来非常困难)之前,请尝试将图例放在不同的位置:

因此,让我们从一个通用示例开始:

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

如果我们做同样的事情,但是使用b@R_371_2419@_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(b@R_371_2419@_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', b@R_371_2419@_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True, shadow=True)
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):
    ax.plot(x, i * x, label='$y = %ix$'%i)

# Shrink current axis by 20%
@R_371_2419@ = ax.get_position()
ax.set_position([@R_371_2419@.x0, @R_371_2419@.y0, @R_371_2419@.width * 0.8, @R_371_2419@.height])

# Put a legend to the right of the current axis
ax.legend(loc='center left', b@R_371_2419@_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
@R_371_2419@ = ax.get_position()
ax.set_position([@R_371_2419@.x0, @R_371_2419@.y0 + @R_371_2419@.height * 0.1,
                 @R_371_2419@.width, @R_371_2419@.height * 0.9])

# Put a legend below current axis
ax.legend(loc='upper center', b@R_371_2419@_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=5)

plt.show()

你可以通过创建字体属性来缩小图例文本:

from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('small')
legend([plot1], "title", prop=fontP) 
# or add prop=fontP to whatever legend() call you already have
python 2022/1/1 18:23:24 有356人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶