Johnson Francis
Johnson Francis

Reputation: 271

Plotting (x,y) point to point connections

I am trying to plot a point to point line plot in python. My data is in a pandas dataframe as below..

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

when I plot this, it is joining from point to point as in the order in the df.

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

enter image description here

But, is there a way, I can plot an order number next to it ? I mean the order it is travelling. Say 1 for the first connection from (0,0) to (0,2) and 2 from (0,2) to (0,1) and so on ?

Upvotes: 0

Views: 150

Answers (2)

Johnson Francis
Johnson Francis

Reputation: 271

I found an easier way to do it.. Thought to share..

fig, ax = plt.subplots()
df.plot('x_coordinate','y_coordinate',ax=ax)
for k, v in df[['x_coordinate','y_coordinate']].iterrows():
    ax.annotate('p'+str(k+1), v)
plt.show()

enter image description here

Upvotes: 0

swatchai
swatchai

Reputation: 18782

The plot is OK. If you want to check how each vertex is plotted, you need modified data. Here is the modified data (x only) and the plot.

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],
})

plotss

Edit

For your new request, the code is modified as follows (full runnable code).

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

updatefig

Upvotes: 1

Related Questions