Reputation: 303
I used to use the following to get the width of the legend in the figure coordinates:
fig = plt.figure()
ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
ax.scatter(xdata, ydata)
legend = ax.legend(loc="lower left", borderaxespad=0)
legend_width = legend.get_window_extent().inverse_transformed(fig.transFigure).width
I've recently updated matplotlib to version 1.5.1. The width (and height) are always 1.0 before transforming, and then after transforming they are extremely small values (width=0.0015625, height=0.0020833) that don't make sense in figure coordinates.
Is there a different way to get the legend width now? Or is this a bug?
Thank you!
Upvotes: 3
Views: 2781
Reputation: 87576
You are getting bit by a performance optimization. We now defer actually rendering the figure as possible. In most interactive cases the this means rendering in deferred until the first time the is repainted by the GUI framework. The exact size of the legend is something that is worked out at draw time, thus when you are asking for the window extent you are getting back place-holder values.
To work around this you can force a rendering by
fig.canvas.draw()
In general you do not want to use get_window_extent
. It is DPI dependent and can lead to some very strange hard to track down bugs. The value returned depends on internal details that are not necessarily user facing and once you have saved the output someplace you can (will) get out of sync.
Upvotes: 2