This is a continuation of the question am having in Legend text alignment renders differently for pdf and png · Issue #15497 · matplotlib/matplotlib · GitHub. With png output, the code example below properly right aligns legend text, but when you change to pdf output it doesn’t work properly. It has to do with pixel unit movement which isn’t appropriate for pdf if your png dpi is different from 100, but I was told to use
fig.dpi_scale_trans but I don’t know how?
text_widths = [text.get_window_extent(fig.canvas.get_renderer()).width for text in legend.get_texts()] max_width = max(text_widths) shifts = [max_width - w for w in text_widths] for i, text in enumerate(legend.get_texts()): text.set_ha('right') text.set_x(shifts[i])