简体   繁体   English

以特定顺序连接散点图matplotlib

[英]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. 我想使用matplotlib绘制元组列表的散点图,其元素为x和y坐标。 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. 我知道连接部分不是实际的python脚本。 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: 当运行此脚本时(没有连接位),我得到下图:

在此处输入图片说明

However, I would like to have the plot appear as: 但是,我希望该图显示为:

在此处输入图片说明

Any ideas how I could go about do this? 我有什么想法可以做到这一点吗?

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. 在这里,我使用了Python词典来保存您的连接信息。

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

在此处输入图片说明

There are duplicate lines here based on how you presented the connectivity, for example, (0,1) and (1,0) . 根据您显示连接性的方式,这里有重复的行,例如(0,1)(1,0) I'm assuming that you'll eventually want to put in the direction, so I left them in. 我以为您最终会朝这个方向发展,所以我把它们留了下来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM