Matplotlib axis text coordinates inconsistency?

筅森魡賤 提交于 2021-01-28 07:51:52

问题


I'm working on a piece of code to automatically align x-axis labels for a variable number of subplots. When I started having trouble setting label positions manually, I checked to be sure I could just transform from one set of coordinates to the other without changing anything, with a code snippet like this:

# xaxes is a list of Axes objects
textCoords = [ax.xaxis.get_label().get_position() for ax in xaxes]
newCoords = [ax.transAxes.inverted().transform(ax.xaxis.get_label().\
    get_transform().transform(c)) for ax,c in zip(xaxes,textCoords)]
for ax,c in zip(xaxes,newCoords): ax.xaxis.set_label_coords(*c)

In theory, this code doesn't change any coordinates; it just gets the coordinates of each label, maps it to Axes coordinates using the Text object's internally-stored transform, and then sets the position. Yet running this code removes my labels entirely, and a little experimentation shows that they go off the bottom edge of the plot.

Have I just misunderstood the transforms involved here?


回答1:


You're understanding the transforms correctly, but there's a caveat to using display coordinates before the plot has been displayed.

The short answer is that putting in a call to plt.draw() before your code snippet above will fix your immediate problem.

You're trying to link the different axes display system through display coordinates. However, before the plot has been drawn the first time, the renderer isn't fully initialized yet, and the display coordinates don't have much meaning.

Can you elaborate a bit more on what you're trying to do? There may be an easier way.

Alternatively, if you want to avoid the extra draw, you can link things through figure coordinates before the plot has been drawn. (They're well defined regardless.)



来源:https://stackoverflow.com/questions/27892824/matplotlib-axis-text-coordinates-inconsistency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!