图例与文本相结合,如何查找图例的宽度和高度

2024-05-17 05:44:08 发布

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

我想让图例和文本框的位置完全一致。在

import matplotlib.pyplot as plt

x = np.arange(10)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for i in range(3):
    ax.plot(x, i * x ** 2, label = '$y = %i x^2$'%i)
ax.set_title('example plot')

#  Shrink the axis by 20% to put legend and text at the bottom 
#+ of the figure
vspace = .2
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * vspace, 
box.width, box.height * (1 - vspace)])

#  Put a legend to the bottom left of the current axis
x, y = 0, 0
#  First solution
leg = ax.legend(loc = 'lower left', bbox_to_anchor = (x, y), \
bbox_transform = plt.gcf().transFigure)

#  Second solution
#leg = ax.legend(loc = (x, y)) , bbox_transform = plt.gcf().transFigure)

#  getting the legend location and size properties using a code line I found
#+ somewhere in SoF
bb = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes)

ax.text(x + bb.width, y, 'some text', transform = plt.gcf().transFigure, \
bbox = dict(boxstyle = 'square', ec = (0, 0, 0), fc = (1, 1, 1)))
plt.show()

这应该将文本放在图例框的右侧,但这不是它的作用。两个盒子没有垂直对齐。 第二种解决方案实际上并不是将图例固定到图形上,而是固定到轴上。在


Tags: thetotextboxfigtransformpltax
1条回答
网友
1楼 · 发布于 2024-05-17 05:44:08

您可以使用帧数据来获得正确的宽度,以便正确定位Text()对象。在

在下面的示例中,我必须对宽度应用1.1因子(这个值我还没有找到如何获得,如果不应用该因子,文本将与图例冲突)。在

还请注意,您必须plt.draw()才能获得正确的宽度值。在

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
fig = plt.figure(figsize=(3, 2))
ax = fig.add_subplot(1, 1, 1)
for i in range(3):
    ax.plot(x, i*x**2, label=r'$y = %i \cdot x^2$'%i)
ax.set_title('example plot')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

x, y = 0.2, 0.5
leg = ax.legend(loc='lower left', bbox_to_anchor=(x, y),
                bbox_transform=fig.transFigure, fontsize=8)
plt.draw()
f = leg.get_frame()
w0, h0 = f.get_width(), f.get_height()
inv = fig.transFigure.inverted()
w, h = inv.transform((w0, h0))

ax.text(x+w*1.1, y+h/2., 'some text', transform=fig.transFigure,
        bbox=dict(boxstyle='square', ec=(0, 0, 0), fc=(1, 1, 1)),
        fontsize=7)

fig.savefig('test.jpg', bbox_inches='tight')

对于x, y = 0.2, 0.5:enter image description here

对于x, y = -0.3, -0.3

enter image description here

相关问题 更多 >