Python 在matplotlib中移动图例框并调整其大小

Python 在matplotlib中移动图例框并调整其大小,python,matplotlib,legend,Python,Matplotlib,Legend,我使用Matplotlib创建绘图,将其另存为SVG,使用Inkscape导出为.pdf+.pdf_-tex,并将.pdf_-tex文件包含在LaTeX文档中 这意味着我可以在标题、图例等中输入LaTeX命令,给出这样的图像 当我在LaTeX文档中使用它时,它呈现为这样。请注意,轴上数字的字体会发生变化,图例中的LaTeX代码将被编译: 绘图代码(此处未显示如何导出到SVG,但可根据要求显示): 正如您所看到的,问题在于图例周围框的对齐方式和大小是错误的。这是因为当图像通过Inkscape+

我使用Matplotlib创建绘图,将其另存为SVG,使用Inkscape导出为.pdf+.pdf_-tex,并将.pdf_-tex文件包含在LaTeX文档中

这意味着我可以在标题、图例等中输入LaTeX命令,给出这样的图像

当我在LaTeX文档中使用它时,它呈现为这样。请注意,轴上数字的字体会发生变化,图例中的LaTeX代码将被编译:

绘图代码(此处未显示如何导出到SVG,但可根据要求显示):

正如您所看到的,问题在于图例周围框的对齐方式和大小是错误的。这是因为当图像通过Inkscape+pdflatex时,标签文本的大小会改变(因为
\footnotesize
等消失,字体大小也会改变)

我发现我可以通过以下两种方式选择标签的位置:

plt.label(loc = 'upper right')
或者如果我想要更多的控制,我可以使用

plt.label(bbox_to_anchor = [0.5, 0.2])
但是我还没有找到任何方法使标签周围的盒子变小。这可能吗

使长方体变小的另一种方法是使用以下内容删除长方体的轮廓:

legend = plt.legend()
legend.get_frame().set_edgecolor('1.0')
然后把标签移到我想要的地方。在这种情况下,我希望能够通过首先让python/matplotlib使用

plt.label(loc = 'upper right')

然后,举例来说,将其向右移动一点。这可能吗?我尝试过使用
将\u bbox\u设置为\u anchor()
将\u bbox\u设置为\u anchor()
,但似乎无法使其工作。

通过绘制图例,然后获取图例的位置,可以在自动放置图例后移动图例。下面是一个例子:

import matplotlib.pyplot as plt
import numpy as np

# Plot data
x = np.linspace(0,1,100)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(221) #small subplot to show how the legend has moved. 

# Create legend
plt.plot(x, y, label = '{\\footnotesize \$y = x^2\$}')
leg = plt.legend( loc = 'upper right')

plt.draw() # Draw the figure so you can find the positon of the legend. 

# Get the bounding box of the original legend
bb = leg.get_bbox_to_anchor().inverse_transformed(ax.transAxes)

# Change to location of the legend. 
xOffset = 1.5
bb.x0 += xOffset
bb.x1 += xOffset
leg.set_bbox_to_anchor(bb, transform = ax.transAxes)


# Update the plot
plt.show()

您可以使用
bbox\u to\u锚定
bbox\u变换
参数来帮助您设置图例的锚定:

ax = plt.gca()
plt.legend(bbox_to_anchor=(1.1, 1.1), bbox_transform=ax.transAxes)

请注意,
(1.1,1.1)
在本例中位于轴坐标中。如果要使用数据坐标,必须使用
bbox\u transform=ax.transData

谢谢。这不允许我在放置后移动图例。顺便说一句,
transAxes
实际上是默认值。@FilipSund,是的,
transAxes
是默认值。。。您可能可以将一个具有4个浮动(x、y、width、height)的元组传递给
bbox\u to\u achor
,这将使您能够更好地控制bbox行为……这看起来很棒。不过,我以前从未见过《传奇补丁》,为什么它没有在书中提到?我不知道。我从Matplotlib用户的电子邮件列表中学到了这个技巧,但我找不到帖子。希望其他人能给出一个更完整的答案!这不适用于get_points(self)1101中的matplotlib版本“1.5.1+1304.gc0728d2”
matplotlib/transforms.py。1102点=自我变换变换(>1103[[p[0,0],p[0,1]],1104[p[1,0],p[0,1]],1105[p[0,0],p[1,1]],TypeError:list index必须是整数,而不是tuple
@DimaLituiev我已经修改了答案,现在它在matplotlib 1.5.1上可以正常工作。在将变量yOffset设置为所需的大小后,您还可以使用:
bb.y0+=yOffset
bb.y1+=yOffset
垂直移动图例。
ax = plt.gca()
plt.legend(bbox_to_anchor=(1.1, 1.1), bbox_transform=ax.transAxes)