简体   繁体   中英

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:

散点图

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.

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM