Skip to main content
 首页 » 编程设计

python之连接 Seaborn 点图中的非相邻数据点

2025年01月19日14hnrainll

我想用 Seaborn 点图绘制分类图,但不相邻的数据点没有用图中的线连接。我想在非相邻点之间进行插值,并以与相邻点连接相同的方式连接它们,我该怎么做?

举个例子:左图和中图,蓝点和绿点应该分别用曲线连接,现在被分成了小块。如何像绘制右侧图像一样绘制左侧图像和中间图像?

fig, axs = plt.subplots(ncols=3, figsize=(10,5)) 
exp_methods = ['fMRI left', 'fMRI right', 'MEG'] 
for i in range(3): 
    experiment = exp_methods[i] 
    dataf = df[df['data']==experiment]     
    sns.pointplot(x='number_of_subjects', y='accuracy', hue='training_size', data=dataf, 
               capsize=0.2, size=6, aspect=0.75, ci=95, legend=False, ax=axs[i]) 

请您参考如下方法:

我不认为有一个选项可以在缺少数据点的地方进行插值,因此该行会停止。 This question 2016 年关于同一主题的问题仍未得到解答。

相反,您可以按照评论中的建议使用 plt.errorbar,或者在之后使用 plt.plot 添加行,同时仍然使用 seaborn 绘制均值和误差酒吧:

import seaborn as sns 
 
tips = sns.load_dataset('tips') 
 
# Create a gap in the data and plot it 
tips.loc[(tips['size'] == 4) & (tips['sex'] == 'Male'), 'size'] = 5 
sns.pointplot('size', 'total_bill', 'sex', tips, dodge=True) 

# Fill gap with manual line plot 
ax = sns.pointplot('size', 'total_bill', 'sex', tips, dodge=True, join=False) 
 
# Loop over the collections of point in the axes and the grouped data frame 
for points, (gender_name, gender_slice) in zip(ax.collections, tips.groupby('sex')): 
    # Retrieve the x axis positions for the points 
    x_coords = [coord[0] for coord in points.get_offsets()] 
    # Manually calculate the mean y-values to use with the line 
    means = gender_slice.groupby(['size']).mean()['total_bill'] 
    ax.plot(x_coords, means, lw=2)