Jack_Bandit
Jack_Bandit

Reputation: 87

Connect scatter plot points in specific order matplotlib

I would like to use matplotlib to plot a scatter plot of a list of tuples, whose elements are x and y coordinates. Their connectivity is determined by another list that says which point is connected to which. What I have so far is this:

import itertools
import matplotlib.pyplot as plt

coords = [(0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (2.0, 1.0), (2.0, 0.0), (3.0, 1.0)]
connectivity = coords[0] <--> coords[1], coords[2]
               coords[1] <--> coords[0], coords[2], coords[3]
               coords[2] <--> coords[0], coords[1], coords[4]
               coords[3] <--> coords[1], coords[3], coords[5]
               coords[4] <--> coords[2], coords[3], coords[5]
               coords[5] <--> coords[3], coords[4]
x, y = zip(*coords)
plt.plot(x, y, '-o')
plt.show()

I know the connectivity part is not actual python script. I included this to show everyone how the points are supposed to be connected. When running this script (without the connectivity bit) I get the below graph:

enter image description here

However, I would like to have the plot appear as:

enter image description here

Any ideas how I could go about do this?

Upvotes: 2

Views: 2176

Answers (1)

tom10
tom10

Reputation: 69182

Just plot each segment separately. This also allows for more flexibility as you can independently change the colors, add direction arrows, etc, for each connection.

Here, I used a Python dictionary to hold your connectivity info.

import matplotlib.pyplot as plt

coords = [(0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (2.0, 1.0), (2.0, 0.0), (3.0, 1.0)]
connectivity = {0: (1,2),     #coords[0] <--> coords[1], coords[2]
                1: (0, 2, 3), #coords[1] <--> coords[0], coords[2], coords[3]
                2: (0, 1, 4), #coords[2] <--> coords[0], coords[1], coords[4]
                3: (1, 3, 5), #coords[3] <--> coords[1], coords[3], coords[5]
                4: (2, 3, 5), #coords[4] <--> coords[2], coords[3], coords[5]
                5: (3, 4)     #coords[5] <--> coords[3], coords[4]
                }
x, y = zip(*coords)
plt.plot(x, y, 'o')  # plot the points alone
for k, v in connectivity.iteritems():
    for i in v:  # plot each connections
        x, y = zip(coords[k], coords[i])
        plt.plot(x, y, 'r')
plt.show()

enter image description here

There are duplicate lines here based on how you presented the connectivity, for example, (0,1) and (1,0). I'm assuming that you'll eventually want to put in the direction, so I left them in.

Upvotes: 3

Related Questions