SJSUHockeyFan
SJSUHockeyFan

Reputation: 21

Using Seaborn to connect corresponding x and y events on a scatter plot with a line

I have a csv file that contains 24 events. The first column is "Event Type", and every event alternates with "Start" and "Finish" with random x and y coordinates for each event. Here is what the CSV file looks like.

CSV File

Here is my code to print a scatter plot using this information:

import seaborn as sns
Events=pd.read_csv('StartFinish.csv')
Scatter = sns.scatterplot(x='xCoordinate', y='yCoordinate', hue='Event Type', data=Events)

Here is the result that I get from running this code in Spyder:

Scatter Plot

My only issue is that I need to add lines that connect each "Start" event with its corresponding "Finish" event. (The corresponding "Finish" event is the one that occurs immediately after.)

How might I go about doing this without importing any libraries besides pandas, numpy, matplotlib.pyplot, and seaborn?

Thanks in advance for any help.

Upvotes: 2

Views: 629

Answers (1)

JavNoor
JavNoor

Reputation: 402

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Replace the following with your own dataframe
# Events=pd.read_csv('StartFinish.csv')
Events = np.random.randint(0, 10, size=(24, 2))
Events = pd.DataFrame(Events, columns=['xCoordinate', 'yCoordinate'])
Events['Event Type'] = 'Start' 
Events.loc[1::2, 'Event Type'] = 'Finish'

Scatter = sns.scatterplot(x='xCoordinate', y='yCoordinate', hue='Event Type', data=Events)
Scatter
for n in range(0, len(Events), 2):
    plt.plot([Events.loc[n, 'xCoordinate'], Events.loc[n+1, 'xCoordinate']], [Events.loc[n, 'yCoordinate'], Events.loc[n+1, 'yCoordinate']], 'k--')

result will be

enter image description here

If you want something more pandas-like, try the following instead:

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Replace the following with your own dataframe
# Events=pd.read_csv('StartFinish.csv')
np.random.seed(0)
Events = np.random.randint(0, 10, size=(24, 2))
Events = pd.DataFrame(Events, columns=['xCoordinate', 'yCoordinate'])
Events['Event Type'] = 'Start' 
Events.loc[1::2, 'Event Type'] = 'Finish'

Scatter = sns.scatterplot(x='xCoordinate', y='yCoordinate', hue='Event Type', data=Events)
Scatter

Events['group'] = Events.index//2
Events.groupby('group').apply(lambda x: plt.plot([x.loc[0, 'xCoordinate'], x.loc[1, 'xCoordinate']], 
                                                 [x.loc[0, 'yCoordinate'], x.loc[1, 'yCoordinate']], 'k--'));

Upvotes: 1

Related Questions