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

2024-04-27 23:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

当我在我的乳胶文档中使用它时,它会像这样呈现。请注意,轴上数字的字体会更改,图例中的乳胶代码也会编译:

plot rendered using 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()

问题是,如您所见,图例周围的框的对齐方式和大小是错误的。这是因为当图像通过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')

然后再把它移到右边。这可能吗?我试过使用get_bbox_to_anchor()set_bbox_to_anchor(),但似乎无法使其工作。


Tags: tosvg绘图pdfplt标签loclabel
2条回答

通过绘制图例并获得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()

legend moved after first drawing

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

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

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

相关问题 更多 >