Home > Mobile >  how to plot xy coordinates for unique row values and trace line according to time?
how to plot xy coordinates for unique row values and trace line according to time?

Time:03-25

say i have:

df ={'animal' : [1, 1, 1, 2, 2, 3, 3, 3, 3],
     'x':[76.551, 76.529, 76.336,76.249,  76.077, 77, 77.02, 77.23, 77.733],
     'y': [151.933, 151.945, 151.970, 152.004, 152.027, 118.369, 118.615, 118.935, 119.115],
    'time': [0, 1, 2, 0, 1, 0, 3,2,5]}
df = pd.DataFrame(df)

how would i plot the xy coordinates for each unique animal? i was trying stuff with .groupby and .unique (not working). i'm able to plot the scatter plot with:

plt.scatter(df[['x']], df[['y']])

but how can i iterate over each unique animal and plot their coordinates (in different colours), then how to draw a line between points according to sequential time points?

CodePudding user response:

You can use:

import matplotlib.pyplot as plt
import matplotlib.cm as cm

cmap = cm.get_cmap('rainbow')
colors = cmap(np.linspace(0.15, 0.85, df['animal'].nunique()))
color_map = dict(zip(df['animal'].unique(), colors))

fig, ax = plt.subplots()
for animal, subdf in df.groupby('animal'):
    ax.plot(subdf['x'], subdf['y'], marker='o', label=animal, c=color_map[animal])
ax.legend()
plt.show()

enter image description here

  • Related