【问题标题】:Is there a python function (preferably seaborn) that can help me connect two sets of points with a line on a scatterplot?是否有python函数(最好是seaborn)可以帮助我将两组点与散点图上的一条线连接起来?
【发布时间】:2019-09-29 06:38:31
【问题描述】:
Index   X1  Y1  X2  Y2

0       3   2    7   8

1      -5   5    4  -6

…       …   …   …   …

n       6  -3   5   -1

有没有办法为索引中的每一行创建一个散点图,其中一条线将(x1, y1) 连接到(x2, y2)? (即(3,2)需要连接(7,8), (-5, 5)需要连接(4,-6)等每一行。我使用的数据集有数百行,我需要用一条线连接每一对点。

我最喜欢的图书馆是 Seaborn。

预期结果应该包括一个散点图,每对点用一条线连接。由于散点图上有数百条线,因此我需要使用减小的线宽和透明度来绘制它。

【问题讨论】:

    标签: python pandas numpy matplotlib seaborn


    【解决方案1】:

    我看到您最好要求seaborn,但如果有必要,也可以仅使用matplotlib 及其LineCollection 几行代码来完成:

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    from matplotlib.collections import LineCollection
    
    # DataFrame provided in example:
    df = pd.DataFrame(
        {'X1': [3, -5, 6], 'Y1': [2, 5, -3], 'X2': [7, 4, 5], 'Y2': [8, -6, -1]})
    
    fig, ax = plt.subplots()
    
    # Plot the (x1, y1) and (x2, y2) points in different colors
    ax.scatter(df['X1'], df['Y1'], color='navy', s=100, lw=0, zorder=5)
    ax.scatter(df['X2'], df['Y2'], color='darkorange', s=100, lw=0, zorder=6)
    
    # Create the segments coordinates :
    segments = df.T.apply(lambda x: [(x.loc['X1'], x['Y1']), (x['X2'], x['Y2'])])
    # Use them in a LineCollection
    lc = LineCollection(segments, zorder=4, cmap=plt.cm.Blues)
    # Set different linewidth if necessary :
    lc.set_linewidths(np.random.random_sample(size=len(segments)) * 2)
    ax.add_collection(lc)
    

    【讨论】:

      【解决方案2】:

      你可以使用双重融化,结合sns.lineplot

      import pandas as pd
      import seaborn as sns
      
      # generate identification column
      df['id'] = df.index
      
      # combine all X values in a column. Same for Y values
      df_x = df.melt(id_vars='id', value_vars=['X1', 'X2']).rename(columns={'value':'X'})[['id', 'X']]
      df_y = df.melt(id_vars='id', value_vars=['Y1', 'Y2']).rename(columns={'value':'Y'})[['Y']]
      
      # combine X-values, Y-values, and identification column
      temp = pd.concat([df_x, df_y], axis=1)
      
      # use lineplot, with different lines for each id:
      sns.lineplot(x='X', y='Y', hue='id', data=temp)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 2020-04-22
        • 2013-12-06
        • 1970-01-01
        • 1970-01-01
        • 2016-07-08
        相关资源
        最近更新 更多