从python中的单独图形连接2个点(matplotlib)

时间:2015-12-03 18:21:34

标签: python matplotlib data-visualization

我正在尝试绘制如下图形,并希望按行连接点。但是,正如您可以看到的一些点(X轴上的0.04以上)部分重叠,并且不允许我们表示它们之间的连接。fig 1.

我想要做的是,制作2个单独的图形,其中1个图形的所有点都高于0.04(因此它将被放大并且点将被分开)而另一个只有左上角的一个点。 fig 2.

注意,点的大小也包含一些含义。所以,我不能让这些点更小或更大。 (除非所有点的变化都是统一的)

这样做的好方法是什么? matplotlib中是否有任何功能提供此类功能?或者除了matplotlib之外还有其他任何python库,我可以用更好的方式做到这一点吗?

1 个答案:

答案 0 :(得分:1)

编辑基于this帖子,比我之前的更好的解决方案可能是:

import matplotlib.pylab as pl
import matplotlib
import numpy as np

pl.close('all')

x = np.linspace(0.019, 0.021, 4)
y = np.linspace(0.09,  0.10,  4)
s = np.random.randint(10, 200, 4)

fig = pl.figure()

ax1=pl.subplot(121)
pl.scatter(x, y, s=s)
pl.xlim(0.01, 0.04)
pl.ylim(0.04, 0.12)
pl.xticks([0.01,0.02,0.03,0.04])
pl.yticks([0.04,0.06,0.08,0.10,0.12])

ax2=pl.subplot(122)
pl.scatter(x, y, s=s)
pl.xlim(0.018, 0.022)
pl.ylim(0.08, 0.11)
pl.xticks([0.018,0.020,0.022])
pl.yticks([0.08,0.095,0.11])

transFigure = fig.transFigure.inverted()
for i in range(x.size):
    xy1 = transFigure.transform(ax1.transData.transform([x[i],y[i]]))
    xy2 = transFigure.transform(ax2.transData.transform([x[i],y[i]]))

    line = matplotlib.lines.Line2D((xy1[0],xy2[0]),(xy1[1],xy2[1]),
                                   transform=fig.transFigure)
    fig.lines.append(line)

enter image description here

另一个(旧的)解决方案:

有趣的问题。我提出了"解决方案"下面(尽管它很漂亮......);它从数据坐标到图形坐标执行ax.transData.transform,并使用ax.annote绘制箭头,但不幸的是,只有保持图形dpi(每英寸点数)相等,此解决方案才有效图ppi(每英寸点数)。

如果我能想出更好的解决方案,我会在这里发布。

import matplotlib.pylab as pl
import numpy as np

x = np.linspace(0.019, 0.021, 4)
y = np.linspace(0.09,  0.10,  4)
s = np.random.randint(10, 200, 4)

# Transform the data coordinates to figure (pixel) coordinates    
def get_display_coordinates(x,y):
    ax = pl.gca()
    xd = np.zeros_like(x)
    yd = np.zeros_like(y)

    for i in range(x.size):
        xd[i], yd[i] = ax.transData.transform([x[i], y[i]])

    return xd, yd

pl.figure(dpi=72)

ax=pl.subplot(121)
sc=pl.scatter(x, y, s=s)
pl.xlim(0.01, 0.04)
pl.ylim(0.04, 0.12)
pl.xticks([0.01,0.02,0.03,0.04])
pl.yticks([0.04,0.06,0.08,0.10,0.12])
xd_1, yd_1 = get_display_coordinates(x,y)

ax=pl.subplot(122)
pl.scatter(x, y, s=s)
pl.xlim(0.018, 0.022)
pl.ylim(0.08, 0.11)
pl.xticks([0.018,0.020,0.022])
pl.yticks([0.08,0.095,0.11])
xd_2, yd_2 = get_display_coordinates(x,y)

for i in range(x.size):
    ax.annotate("",
                xy=(xd_2[i], yd_2[i]), xycoords='figure pixels',
                xytext=(xd_1[i], yd_1[i]), textcoords='figure pixels',
                arrowprops=dict(arrowstyle="->", connectionstyle="arc3"))

pl.savefig('test.png', dpi=72)

enter image description here