python - 按特定顺序连接散点图点 matplotlib

标签 python matplotlib

我想使用 matplotlib 绘制元组列表的散点图,其元素是 x 和 y 坐标。它们的连接性由另一个列表确定,该列表说明哪个点连接到哪个点。到目前为止我所拥有的是:

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

我知道连接部分不是实际的 python 脚本。我添加此内容是为了向大家展示这些点应该如何连接。运行此脚本时(没有连接位),我得到下图:

enter image description here

但是,我希望情节显示为:

enter image description here

我有什么想法可以做到这一点吗?

最佳答案

只需分别绘制每个片段即可。这还提供了更大的灵活性,因为您可以为每个连接独立更改颜色、添加方向箭头等。

在这里,我使用 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()

enter image description here

根据您呈现连接的方式,此处存在重复行,例如 (0,1)(1,0)。我假设您最终会想要指明方向,所以我把它们留在了里面。

关于python - 按特定顺序连接散点图点 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335601/

相关文章:

python - 如何在Python中对大量点进行反向地理编码?

python - 使用子图绘制 pandas 数据框时出现 IndexError

python PIL : best scaling method that preserves lines

python - 如何在seaborn中设置日期时间xlim

python - Matplotlib 弃用 在 plt.show() 中设置值时发出警告。关键词是什么?

python - 离线显示MPLD3图

python - Cygwin gcc 问题 - 找不到 Python.h

python - 从 python 中的 gzip 文件中读取

python - pyschool 错了吗?

python - Networkx 图在不同平台上的大小不同