【问题标题】:Using Seaborn to connect corresponding x and y events on a scatter plot with a line使用 Seaborn 将散点图上对应的 x 和 y 事件用一条线连接起来
【发布时间】:2019-11-27 20:37:36
【问题描述】:

我有一个包含 24 个事件的 csv 文件。第一列是“事件类型”,每个事件交替显示“开始”和“完成”,每个事件的 x 和 y 坐标都是随机的。这是 CSV 文件的样子。

CSV File

这是我使用此信息打印散点图的代码:

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

这是我在 Spyder 中运行这段代码得到的结果:

我唯一的问题是我需要添加将每个“开始”事件与其对应的“完成”事件连接起来的行。 (相应的“完成”事件是紧随其后发生的事件。)

在不导入除了 pandas、numpy、matplotlib.pyplot 和 seaborn 之外的任何库的情况下,我如何才能做到这一点?

提前感谢您的帮助。

【问题讨论】:

  • 不要只包含数据的图片。将它们复制并粘贴为文本。
  • 最好将示例数据发布为代码而不是 csv 的图片。

标签: python seaborn


【解决方案1】:
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--')

结果将是

如果您想要更像熊猫的东西,请尝试以下方法:

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

【讨论】:

  • 那个单点可能是一个起点和终点相等的点。
猜你喜欢
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2019-09-29
相关资源
最近更新 更多