首页 > 解决方案 > 在 Python 中绘制连接点的 xy 网格

问题描述

这里是 Python 新手!

我希望你能帮忙。我正在尝试创建一个包含以下列的数据框:

我这样做是因为我正在尝试使用这些坐标创建一个网格,将每个坐标显示为一个点,并将每个连接显示为一条线段。

这是我的模拟尝试:

import pandas as pd
origin = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2),
          (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]
destination = [(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),
               (0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1),
               (0,2),(0,2),(0,2),(0,2),(0,2),(0,2),(0,2),(0,2),(0,2),
               (1,0),(1,0),(1,0),(1,0),(1,0),(1,0),(1,0),(1,0),(1,0),
               (1,1),(1,1),(1,1),(1,1),(1,1),(1,1),(1,1),(1,1),(1,1),
               (1,2),(1,2),(1,2),(1,2),(1,2),(1,2),(1,2),(1,2),(1,2),
               (2,0),(2,0),(2,0),(2,0),(2,0),(2,0),(2,0),(2,0),(2,0),
               (2,1),(2,1),(2,1),(2,1),(2,1),(2,1),(2,1),(2,1),(2,1),
               (2,2),(2,2),(2,2),(2,2),(2,2),(2,2),(2,2),(2,2),(2,2)]
connected = np.zeros(81)
network = pd.DataFrame({'origin': origin, 'destination': destination, 'connected': connected})
for ind in network.index:
    if network['origin'][ind] == network['destination'][ind]:
        network['connected'][ind] = 0
    else:
        network['connected'][ind] = np.random.randint(0,2)

我有几个问题:

  1. 如何使用 pyplot 绘制这些点和连接?
  2. 我的代码随机连接点,无论它们是否相邻,但我需要它们仅在对角线或正交相邻的情况下随机连接(例如,(0,0)无法连接到(2,1))。我怎么做?
  3. 有没有更好/更优雅的方式来呈现这些数据,而不是我在这里共享的 3 列数据框?
  4. 我的网格将是一个 25x25 的网格,因此坐标列表会更长,我怎样才能自动生成这些坐标而不是手动写出来?

在此先感谢您,非常感谢您的帮助!

标签: pythonpandasmatplotlib

解决方案


这是您连接它们的方式:

fig = plt.figure()
ax = fig.add_subplot(111)
assert len(origin) == len(destination)
for i in range(len(origin)):
    plt.plot(origin[i], destination[i])
plt.show()

这使

在此处输入图像描述


推荐阅读