pault543
pault543

Reputation: 211

Matplotlib: Can a plot a line from one set of axes to another?

I wish to plot marker "x" at say [100,100] and then plot "o" at [20%, 30%] (different axes, same plot) and connect them with a line. I can do something similar on the same axes (with the same units) with one call to plot the line, another call to plot the "x" and a final call to plot the "o".

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

However, how can I get the line to go from one set of axes to the other?

Upvotes: 1

Views: 1070

Answers (3)

shaneb
shaneb

Reputation: 1474

For anyone who arrived at this looking to plot high-dimensional data on one figure, by drawing lines connecting points in the different dimensions, note that what you are looking for is called a "Parallel Coordinates Plot".

There are possible solutions in matplotlib, as well as solutions using pandas and plotly:

Parallel Coordinates plot in Matplotlib

Upvotes: 0

btel
btel

Reputation: 5693

You can use annotate to draw single lines:

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='-'))

which produces this result:

matplotlib plot

Upvotes: 5

Dman2
Dman2

Reputation: 740

I'm not sure I understood your question completely, but put this together to see if it is what you were looking for?

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()

Upvotes: 0

Related Questions