Python 图例与文字相结合,如何查找图例的宽度和高度
我想设置图例和文本框的位置和样式完全相同,特别是后者使文本对齐Python 图例与文字相结合,如何查找图例的宽度和高度,python,matplotlib,plot,legend,legend-properties,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 ax
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()
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
:
我没有得到同样的结果。我使用的是matplotlib 1.1.1;哪一个是你的?你能把f,w0,h0,inv,w,h的值加进去吗?另外,如果不使用figsize=(3,2),您会得到相同的结果吗?@user1850133我使用的是matplotlib 1.3.1,让我们在中继续此聊天