Search code examples
pythonpandasmatplotlibscatter-plot

Add arrows on scatter plot between points Pandas


I have a dataframe:

import pandas as pd 
d = {'year': [2021, 2021, 2021, 2021, 2021], 'month': [3, 4, 5, 8, 9], 'day': [23, 14, 6, 11, 3],
     'latitude':[38.23750, 34.07029, 49.71443, 37.77493, 40.71427], 
     'longitude':[-117.39588, -104.35108, 7.30776,-122.41942, -74.00597],
    'brightness':[300, 20, 100, 150, 80]}
df = pd.DataFrame(data=d)
df['datatime'] = pd.to_datetime(df[['year', 'month', 'day']])

I'm plotting the data on a scatter plot, latitude on the y-axis, longitude on the x-axis:

df.plot(x="longitude", y="latitude", kind="scatter", c="brightness", s="brightness", alpha=0.5,
        colormap="cool")

enter image description here

But I want to add arrows between the dots starting from an early date. So the arrows indicate the transitions in datatime. I want something like this (I added arrows in paint): enter image description here


Solution

  • Assuming your dates are sorted (if not, just sort by date):

    ax = df.plot(x="longitude", y="latitude", kind="scatter",
                 c="brightness", s="brightness", alpha=0.5,
                 colormap="cool")
    
    prev = None
    for row in df[::-1].itertuples():
        if prev:
            ax.annotate('',
                        xy=(prev.longitude, prev.latitude),
                        xytext=(row.longitude, row.latitude),
                        arrowprops=dict(arrowstyle="->"),
                        color='k',
                       )
        prev= row
    

    output:

    arrows