【问题标题】:Combining regplot with piecewise linear regression on a Facetgrid with seaborn在带有 seaborn 的 Facetgrid 上将 regplot 与分段线性回归相结合
【发布时间】:2016-08-07 09:49:23
【问题描述】:

我想在网格上绘制我的数据以及相关的误差条和通过每个时间点的平均值进行的分段线性回归。我将我的数据保存在 pandas 数据框中,并希望我们 seaborn 来完成这项工作。

如果我使用 seaborns factorplot 我会接近。

g = sns.factorplot(x="Time", y='value', hue="Name",
                col="PEAK", data=meltdf,
                size=4, aspect=1.0,col_wrap=3,sharey=False,scale=0.7)

output for the factorplot

但请注意,我的 xaxis 没有正确缩放(这是有道理的,因为 factorplot 是为分类比较而设计的)

如果我改为创建 FacetGrid 并将 regplot 和 plt.plot 映射到网格上,我会在 x 轴上得到正确的间距并保留误差线等,但线性回归不是我想要的

meltdf = pd.melt(Conc_norm.drop(['GLC','pan','Ratio %'],axis=1),
id_vars=['Name','Time'], var_name='PEAK')

g = sns.FacetGrid(meltdf, col="PEAK",hue='Name', col_wrap=4,sharey=False)
g.map(sns.regplot, "Time", "value",fit_reg=False, x_estimator=np.mean);
g.map(plt.plot, "Time", "value");

output for the Facetgrid mapped with regplot and plt.plot

现在问题来了: 如何在图中的点之间绘制分段线性回归?

谢谢,

【问题讨论】:

  • 我认为如果您在绘图之前对Time 上的数据框进行排序,您的第二种方法应该可以工作。
  • 按时排序会改善外观,但仍会在所有时间、值坐标中绘制一条线。我想要的是绘制一些东西。 df.groupby('Time').mean() 但我不知道该怎么做
  • 啊,是的,那你需要写一个小绘图函数。

标签: python pandas seaborn


【解决方案1】:

在网上搜索并阅读了 mwaskom 的许多优秀答案后,我似乎找到了一个可行的解决方案

def _plotmean(x, *args, **kwargs):
    ax = plt.gca()
    data = kwargs.pop('data')
    data = data.groupby(x).mean()
    data.plot(ax=ax, **kwargs)

Conc_norm.sort_values('Time', inplace=True)

meltdf = pd.melt(Conc_norm.drop(['GLC','pan','Ratio %'], axis=1),
                 id_vars=['Name','Time'], var_name='PEAK')

g = sns.FacetGrid(meltdf, col="PEAK", hue='Name', col_wrap=3,sharey=False)
g.map(sns.regplot, "Time", "value", fit_reg=False, x_estimator=np.mean)
g.map_dataframe(_plotmean, "Time")
g.add_legend()

working output

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2019-08-01
    • 2017-11-05
    • 2018-11-18
    • 2015-08-01
    相关资源
    最近更新 更多