我有一个情节,其图例固定在右上角:如何展开图例以适应图表的高度?
borderaxespad=0. 会水平扩展它,但我找不到相当于垂直扩展它.
我正在使用matplotlib 2.0
示例代码:
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
data = [np.sin(x * np.pi/float(el)) for el in range(1, 5)]
fig, ax = plt.subplots(1)
for key, el in enumerate(data):
ax.plot(x, el, label=str(key))
ax.legend(bbox_to_anchor=(1.04,1), loc="upper left", borderaxespad=0., mode='expand')
plt.tight_layout(rect=[0,0,0.8,1])
Run Code Online (Sandbox Code Playgroud)
哪个产生:
首先解释问题的输出:当使用 2-tuple 表示法时bbox_to_anchor,会创建一个没有范围的边界框。该mode="expand"会水平扩展的传说到这个边界框,它具有零扩展,它有效地收缩至零大小。
问题是mode="expand"只会水平扩展图例。从文档:
mode: {“expand”, None}
如果模式设置为“expand”,图例将水平扩展以填充轴区域(如果定义了图例的大小,则为 bbox_to_anchor)。
对于解决方案,您需要深入研究图例内部结构。首先,您需要使用 4 元组设置 bbox-to-anchor,同时指定 bbox 的宽度和高度 bbox_to_anchor=(x0,y0,width,height),其中所有数字都在标准化轴坐标中。然后你需要计算图例的高度_legend_box。由于设置了一些填充,您需要从边界框的高度中减去该填充。为了计算填充,必须知道当前图例的字体大小。所有这一切都必须在轴的位置最后一次改变之后发生。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
data = [np.sin(x * np.pi/float(el)) for el in range(1, 5)]
fig, ax = plt.subplots(1)
for key, el in enumerate(data):
ax.plot(x, el, label=str(key))
# legend:
leg = ax.legend(bbox_to_anchor=(1.04,0.0,0.2,1), loc="lower left",
borderaxespad=0, mode='expand')
plt.tight_layout(rect=[0,0,0.8,1])
# do this after calling tight layout or changing axes positions in any way:
fontsize = fig.canvas.get_renderer().points_to_pixels(leg._fontsize)
pad = 2 * (leg.borderaxespad + leg.borderpad) * fontsize
leg._legend_box.set_height(leg.get_bbox_to_anchor().height-pad)
plt.show()
Run Code Online (Sandbox Code Playgroud)