我试图在matplotlib轴图例中向右对齐条目(默认情况下,它们是左对齐的),但似乎找不到任何方法。我的设置如下:
(我已经使用my_fig ()命令向ax.plot轴添加了数据和标签)
ax = my_fig.get_axes()[0]
legend_font = FontProperties(size=10)
ax.legend(prop=legend_font, num_points=1, markerscale=0.5)matplotlib轴的文档中有一个图例关键字参数列表,但是似乎没有任何直接的方法来设置图例条目的对齐方式。有人知道后门的方法吗?谢谢。
编辑:
为了澄清我想要实现的目标,现在我的传奇是这样的:
机动:2011年10月12日12:00世界协调时偏差:14-10月-2011年06:00世界协调时
我想让它看起来像:
机动:2011年10月12日12:00世界协调时偏差:14-10月-2011年06:00世界协调时
发布于 2011-11-10 10:30:28
你要找的后门是:
# get the width of your widest label, since every label will need
# to shift by this amount after we align to the right
shift = max([t.get_window_extent().width for t in legend.get_texts()])
for t in legend.get_texts():
t.set_ha('right') # ha is alias for horizontalalignment
t.set_position((shift,0))发布于 2013-05-31 13:18:27
我试着做这个例子,但我做不到。
至少由于matplotlib版本1.1.1 (可能更早),我们需要一个专用的呈现器实例。注意你的后端,它定义了渲染器。取决于后端,输出在屏幕上可能看起来很好,但像PDF一样令人沮丧。
# get the width of your widest label, since every label will need
#to shift by this amount after we align to the right
renderer = figure.canvas.get_renderer()
shift = max([t.get_window_extent(renderer).width for t in legend.get_texts()])
for t in legend.get_texts():
t.set_ha('right') # ha is alias for horizontalalignment
t.set_position((shift,0))发布于 2022-09-30 15:44:37
保罗·伊万诺夫的回答把我带到了正确的方向。但我需要稍微调整一下:
max_shift = max([t.get_window_extent().width for t in legend_obj.get_texts()])
for t in legend_obj.get_texts():
t.set_ha('right') # ha is alias for horizontalalignment
temp_shift = max_shift - t.get_window_extent().width
t.set_position((temp_shift, 0))更改意味着我们根据每个对象的宽度和图例文本的最大宽度为其设置不同的移位。
对于那些获得Cannot get window extent w/o renderer错误的人,添加一个plt.pause(0.1) :)
https://stackoverflow.com/questions/7936034
复制相似问题