首页 > 解决方案 > 用python绘制(x,y)点对点连接

问题描述

我正在尝试在 python 中绘制点对点线图。我的数据在熊猫数据框中,如下所示..

df = pd.DataFrame({
'x_coordinate': [0, 0, 0, 0, 1, 1,-1,-1,-2,0],
'y_coordinate': [0, 2, 1, 3,  3, 1,1,-2,2,-1],
})
print(df)

      x_coordinate  y_coordinate
   0             0             0
   1             0             2
   2             0             1
   3             0             3
   4             1             3
   5             1             1
   6            -1             1
   7            -1            -2
   8            -2             2
   9             0            -1

当我绘制它时,它会按照 df 中的顺序从点到点连接。

df.plot('x_coordinate','y_coordinate')

在此处输入图像描述

但是,有没有办法,我可以在它旁边绘制一个订单号?我的意思是它旅行的顺序。从 (0,0) 到 (0,2) 的第一个连接说 1 和从 (0,2) 到 (0,1) 的 2 等等?

标签: pythonpandasnumpymatplotlib

解决方案


剧情还行。如果要检查每个顶点的绘制方式,则需要修改数据。这是修改后的数据(仅限 x)和绘图。

df = pd.DataFrame({
'x_coordinate': [0.1, 0.2, 0.3, 0.4, 1.5, 1.6,-1.7,-1.8,-2.9,0.1],
'y_coordinate': [0, 2, 1, 3,  3, 1,1,-2,2,-1],
})

地块

编辑

对于您的新请求,代码修改如下(完整的可运行代码)。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame({
'x_coordinate': [0.1, 0.2, 0.3, 0.4, 1.5, 1.6,-1.7,-1.8,-2.9,0.1],
'y_coordinate': [0, 2, 1, 3,  3, 1,1,-2,2,-1],
})

fig = plt.figure(figsize=(6,5))
ax1 = fig.add_subplot(1, 1, 1)

df.plot('x_coordinate','y_coordinate', legend=False, ax=ax1)

for ea in zip(np.array((range(len(df)))), df.x_coordinate.values, df.y_coordinate.values):
    text, x, y = "P"+str(ea[0]), ea[1], ea[2]
    ax1.annotate(text, (x,y))

更新无花果


推荐阅读