Matplotlib:可以绘制从一组轴到另一组的线吗?

时间:2013-09-02 10:53:08

标签: python matplotlib plot

我希望在[100,100]处绘制标记“x”,然后在[20%,30%](不同的轴,相同的图)上绘制“o”并用线连接它们。我可以在相同的轴上(使用相同的单位)执行类似的操作,一次调用绘制线,另一次调用绘制“x”,最后调用绘制“o”。

ax.plot(x,y,"-")
ax.scatter(x[0], y[0], marker='x')
ax.scatter(x[1], y[1], marker='o')

但是,如何让这条线从一组轴到另一组呢?

3 个答案:

答案 0 :(得分:1)

您可以使用annotate绘制单行:

ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

x = [[1, 2], [3,4]]
y = [[5, 6], [6,4]]

ax1.scatter(x[0], y[0])
ax2.scatter(x[1], y[1])


ax1.annotate('', xy=(x[0][0], y[0][0]), xytext=(x[1][0], y[1][0]), xycoords=ax1.transData, 
         textcoords=ax2.transData, 
         arrowprops=dict(facecolor='black', arrowstyle='-',, clip_on=False))
ax2.annotate('', xy=(x[0][0], y[0][0]), xytext=(x[1][0], y[1][0]), xycoords=ax1.transData, 
         textcoords=ax2.transData, 
         arrowprops=dict(facecolor='black', arrowstyle='-'))

产生这个结果:

matplotlib plot

答案 1 :(得分:0)

我不确定我完全理解你的问题,但把它们放在一起看看它是不是你想要的?

import pylab

#generate array of data for example
import numpy as np
x = np.arange(1,250,1)
y = np.arange(1,250,1)

#find marker for your 'x' points
x_marker_location = 100
x_marker_x = x[np.where(x==x_marker_location)]  # np.where looks for location in your data where array equals a value. Alternatively, x_marker_x and y would just be a coordinate value.
x_marker_y = y[np.where(y==x_marker_location)]

#create scaling factors
o_marker_scale_x = 0.2
o_marker_scale_y = 0.3
#find marker for your 'o' points
o_marker_x = x[np.where(x==x_marker_location*o_marker_scale_x)]
o_marker_y = y[np.where(y==x_marker_location*o_marker_scale_y)]

#draw line of all data
pylab.plot(x,y,"-",color='black')
#draw points interested in
pylab.scatter(x_marker_x, x_marker_y, marker='x')
pylab.scatter(o_marker_x, o_marker_y, marker='o')
#draw connecting line - answer to question?
pylab.plot([x_marker_x,o_marker_x],[x_marker_y,o_marker_y],'-',color='red')

#show plot
pylab.show()

答案 2 :(得分:0)

对于想要在一个图形上绘制高维数据的任何人来说,通过绘制连接不同维度中的点的线,请注意,您正在寻找的是“平行坐标图”。

matplotlib 中有可能的解决方案,也有使用 pandas 和 plotly 的解决方案:

Parallel Coordinates plot in Matplotlib