Pyplot和Seaborn - 如何向图例添加标记,当它们是由Seaborn生成时

2024-10-02 00:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一张图表上绘制5组数据。对于每一组数据,我需要绘制点的散点图(我使用seaborn.regplot)和一个单独拟合到这些点的线函数。在

问题是我可以将这些线添加到图例中,但是我不能从regplot中添加标记,因为我没有任何对象句柄。这是我的代码:

    f, ax = plt.subplots()

    #Plotting the scatter points onto the axes object ax
    sns.regplot(x='logF', y='R', data=MeanParams[(0 < MeanParams.M) & (0.2 > MeanParams.M)], 
            fit_reg=False, color='g', marker='+', ax=ax)
    sns.regplot(x='logF', y='R', data=MeanParams[(0.2 < MeanParams.M) & (0.5 > MeanParams.M)], 
            fit_reg=False, color='y', marker='x', ax=ax)
    sns.regplot(x='logF', y='R', data=MeanParams[(0.5 < MeanParams.M) & (1.5 > MeanParams.M)], 
            fit_reg=False, color='r', marker='x', ax=ax)
    sns.regplot(x='logF', y='R', data=MeanParams[(1.5 < MeanParams.M) & (3.5 > MeanParams.M)], 
            fit_reg=False, color='b', marker='x', ax=ax)
    sns.regplot(x='logF', y='R', data=MeanParams[(3.5 < MeanParams.M)], 
            fit_reg=False, color='k', marker='+', ax=ax)

    #plotting the lines onto the same axes object
    line1, = ax.plot(x, y_0, 'k-', linewidth=2)
    line2, = ax.plot(x, y_1, 'k--', linewidth=2)
    line3, = ax.plot(x, y_2, 'k-.', linewidth=3)
    line4, = ax.plot(x, y_3, 'k:', linewidth=3)
    line5, = ax.plot(x, y_4, 'r--', linewidth=2)

    #creating the legend
    ax.legend((line1,line2,line3,line4,line5), 
         (r'0.0 - 0.2', r'0.2 - 0.5', r'0.5 - 1.5', r'1.5 - 3.5', r'3.5 + '), 
         title='Mass Range', loc='upper left')

如您所见,我在ax.plot()生成的line对象上有句柄,但是由于我用seaborn.regplot()绘制散点图,所以我对标记没有任何句柄。在

解决这一问题的一个简单方法是通透性地使用pyplot分散。但我想我只是好奇地问,有没有一种方法可以把线/标记对象拉出来,这样我就可以把它们也放入一个传说中?在


Tags: thefalsedataplot绘制regaxmarker

热门问题