图例结合文字,如何找到图例的宽度和高度

时间:2014-05-22 10:13:22

标签: python matplotlib plot legend legend-properties

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

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

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

1 个答案:

答案 0 :(得分: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')

for x, y = 0.2, 0.5enter image description here

代表x, y = -0.3, -0.3

enter image description here