我正在尝试修复 Matplotlib (Python 2.7) 中图例框的宽度。这是我正在使用的代码的一个简单示例:
import numpy as np
import pylab as plt
fig = plt.figure(figsize=(8.5, 8.5))
ax = fig.add_axes([0.0882, 0.0588, 0.8882, 0.9118])
x = np.array([0,1,2,33])
y = np.array([0.1,2,4,8])
z = np.array([0,1,3.7,7])
t = np.array([0.5,1,12,41])
v = np.array([0.9,7,24,54])
a = np.array([0.2,11,17,61])
q = np.array([0.4,17,15,80])
r = np.array([0.9,3.7,18,44])
s = np.array([0.2,10,19,31])
y1 = y+1
z1 = z+1
t1 = t+1
v1 = v+1
a1 = a+1
q1 = q+1
r1 = r+1
s1 = s+1
ax.plot(x,y,label='y')
ax.plot(x,z,label='z')
ax.plot(x,t,label='t')
ax.plot(x,v,label='v')
ax.plot(x,a,label='a')
ax.plot(x,y1,label='y1')
ax.plot(x,z1,label='z1')
ax.plot(x,t1,label='t1')
ax.plot(x,v1,label='v1')
ax.plot(x,a1,label='a1')
ax.plot(x,q1,label='q1')
ax.plot(x,r1,label='r1')
ax.plot(x,s1,label='s1')
lg = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=10)
fig.savefig('A_test_position.png', facecolor='white', dpi = 300, bbox_inches='tight')
当我只保留前 3 个 ax.plot() 语句时,我得到 .但是,当我包含所有 ax.plot() 语句时,输出变为
问题: 我需要将图例框用于:
- 从 x 轴上的 0 开始
- 以 x 轴上的最大 x 值结束(在本例中,最大值为 35)
- 在 x 轴上达到最大值后换行
当条目数量较少时(例如第一个图),我希望图例居中。目前我的代码为此正常工作,因此我不需要更改此行为。但是,当图例需要环绕到新行(第二个图)的条目太多时,我需要更改行为。
这如何在 Matplotlib 中完成?有没有办法指定图例框的大小?
请您参考如下方法:
一个解决方案是迭代 ncol 参数,直到图例的宽度变得大于斧头的宽度。然后,使用为 ncol 和 mode='expand' 选项找到的最佳值,使图例扩展到斧头的整个宽度。如果所有条目都可以放在一行中,您的“居中布局”将保留,不会将图例扩展到斧头的宽度。
下面是一个代码示例,展示了如何做到这一点:
ncol = 1
lgwidth_old = 0.
renderer = fig.canvas.get_renderer()
while True:
lg = ax.legend(loc='upper center', bbox_to_anchor=(0., -0.05, 1., 0.),
borderaxespad=0, ncol=ncol)
fig.canvas.draw()
lgbbox = lg.get_window_extent(renderer).inverse_transformed(ax.transAxes)
if lgwidth_old == lgbbox.width:
# All the entries fit within a single row. Keep the legend
# as is and break the loop.
break
if lgbbox.width < 1:
# The width of the legend is still smaller than that of the axe.
# Continue iterating.
ncol += 1
lgwidth_old = lgbbox.width
else:
# The width of the legend is larger than that of the axe.
# Backtrack ncol, plot the legend so it span the entire width of
# the axe, and break the loop.
ncol -= 1
lg = ax.legend(loc='upper center', bbox_to_anchor=(0., -0.05, 1., 0.),
borderaxespad=0, ncol=ncol, mode='expand')
break
if ncol > 100:
print('Number max of iteration reached. Something is wrong.')
break
结果(当添加到您的代码中时):
