matplotlib 中图形坐标不一致,纵横比相等 [英] Inconsistent figure coordinates in matplotlib with equal aspect ratio

查看:30
本文介绍了matplotlib 中图形坐标不一致,纵横比相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在准备一个带有从一个到另一个的子图和箭头的图形,在这里解决:

最简单的解决方案是致电

  fig.canvas.draw()

紧接在 plot 命令之后,但在进行任何转换工作之前.通过这种方式,人物被应用到画布上,并具有相同的外观.从现在开始,可以使用正确的转换.

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] 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.

这篇关于matplotlib 中图形坐标不一致,纵横比相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆