我想让图例和文本框的位置完全一致。在
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()
这应该将文本放在图例框的右侧,但这不是它的作用。两个盒子没有垂直对齐。 第二种解决方案实际上并不是将图例固定到图形上,而是固定到轴上。在
您可以使用帧数据来获得正确的宽度,以便正确定位
Text()
对象。在在下面的示例中,我必须对宽度应用
1.1
因子(这个值我还没有找到如何获得,如果不应用该因子,文本将与图例冲突)。在还请注意,您必须
plt.draw()
才能获得正确的宽度值。在对于
x, y = 0.2, 0.5
:对于
x, y = -0.3, -0.3
:相关问题 更多 >
编程相关推荐