简体   繁体   中英

Inconsistent figure coordinates in matplotlib with equal aspect ratio

I'm preparing a figure with subplots and arrows going from one to another, which is addressed here: Drawing lines between two plots in Matplotlib

In my figure, the subplots all have an equal aspect ratio, and this seems to mess up the transformation from data coordinates to figure coordinates, so the Line2D objects I create are not going where I want them to.

Here's a simple example (modified from the above link) that demonstrates the problem and doesn't even require subplots:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(6,4))
ax = fig.add_subplot(111)
ax.set_aspect('equal')

x = [0.2, 0.9]
y = [0.3, 0.7]

ax.plot(x,y,'k--', lw=4)

transFigure = fig.transFigure.inverted()

coord1 = transFigure.transform(ax.transData.transform([x[0],y[0]]))
coord2 = transFigure.transform(ax.transData.transform([x[1],y[1]]))

line = matplotlib.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]),
                           transform=fig.transFigure)

fig.lines.append(line)

plt.show()

By changing the dimensions of the figure it's easy to see that the Line2D object changes slope while the plot on the axes maintains its slope (as desired for an equal aspect ratio).

Is there a straightforward way to get these figure coordinates (or use a different transformation) such that the Line2D object stays consistent with the plotted line?

The problem is that when setting the aspect to equal the dimensions and positions of the axes can only be determined by matplotlib once something is drawn onto the canvas. Before plotting the data, it cannot know where the axes would reside in the final figure. Using more extreme points like x = [0.2, 0.9]; y = [0.55, 0.6] x = [0.2, 0.9]; y = [0.55, 0.6] make that clearer.

在此输入图像描述

The easiest solution is to call

fig.canvas.draw()

right after the plot command but before doing any transformation works. In this way, the figure gets drawn to the canvas, applying the equal aspect; and from this point on, the correct transformations are available.

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM