移动并调整matplotlib中的图例框大小

Fil*_* S. 11 python matplotlib legend

我正在使用Matplotlib创建绘图,我保存为SVG,使用Inkscape导出到.pdf + .pdf_tex,并在LaTeX文档中包含.pdf_tex文件.

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

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

使用LaTeX渲染的绘图

图的代码(如何导出到SVG这里没有显示,但可以根据要求显示):

import numpy as np
x = np.linspace(0,1,100)
y = x**2

import matplotlib.pyplot as plt
plt.plot(x, y, label = '{\\footnotesize \$y = x^2\$}')
plt.legend(loc = 'best')
plt.show()
Run Code Online (Sandbox Code Playgroud)

问题是,正如您所看到的那样,图例周围框的对齐和大小是错误的.这是因为当图像通过Inkscape + pdflatex时,标签文本的\footnotesize大小会发生变化(因为等等会消失,并且字体大小会发生变化).

我已经发现我可以选择标签的位置

plt.label(loc = 'upper right')
Run Code Online (Sandbox Code Playgroud)

或者如果我想要更多控制我可以使用

plt.label(bbox_to_anchor = [0.5, 0.2])
Run Code Online (Sandbox Code Playgroud)

但我没有找到任何方法使标签周围的盒子变小.这可能吗?

使盒子变小的另一种方法是使用类似的东西去除盒子的轮廓

legend = plt.legend()
legend.get_frame().set_edgecolor('1.0')
Run Code Online (Sandbox Code Playgroud)

然后将标签移动到我想要的位置.在这种情况下,我希望能够通过首先让python/matplotlib使用它来设置标签的位置

plt.label(loc = 'upper right')
Run Code Online (Sandbox Code Playgroud)

然后例如将它向右移动一点.这可能吗?我已经尝试使用get_bbox_to_anchor()set_bbox_to_anchor(),但似乎无法得到它的工作.

Mol*_*lly 16

您可以通过绘制后自动放置图例,然后获取bbox位置来移动图例.这是一个例子:

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()
Run Code Online (Sandbox Code Playgroud)

第一次绘图后移动的图例


Sau*_*tro 8

您可以使用bbox_to_anchorbbox_transform参数来帮助您设置图例的锚点:

ax = plt.gca()
plt.legend(bbox_to_anchor=(1.1, 1.1), bbox_transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)

请注意,(1.1, 1.1)在此示例中位于轴坐标中.如果您希望使用数据坐标,则必须使用bbox_transform=ax.transData.