简体   繁体   English

使用 Seaborn 将散点图上相应的 x 和 y 事件与一条线连接起来

[英]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.我有一个包含 24 个事件的 csv 文件。 The first column is "Event Type", and every event alternates with "Start" and "Finish" with random x and y coordinates for each event.第一列是“事件类型”,每个事件与“开始”和“完成”交替,每个事件的 x 和 y 坐标随机。 Here is what the CSV file looks like.这是 CSV 文件的样子。

CSV File CSV文件

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:这是我在 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?除了pandas、numpy、matplotlib.pyplot 和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--'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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