1

我想将图例和文本框的位置和样式设置为完全相同,后者尤其是为了使文本对齐。

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()

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

4

1 回答 1

0

您可以使用帧数据来获得正确的宽度,以便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在此处输入图像描述

对于x, y = -0.3, -0.3

在此处输入图像描述

于 2014-05-23T06:54:48.057 回答