【问题标题】:In a scatterplot, how do I plot a line that is an average of the all vertical coordinates of datapoints that has the same x coordinate在散点图中,如何绘制一条线,该线是具有相同 x 坐标的数据点的所有垂直坐标的平均值
【发布时间】:2023-01-26 04:43:24
【问题描述】:

我想要如下图所示的图,其中蓝线是通过绘制具有相同 x 坐标值的数据点的所有 y 坐标值的平均值生成的平均线。

我试过下面的代码

window_size = 10
df_avg = pd.DataFrame(columns=df.columns)

for col in df.columns:
    df_avg[col] = df[col].rolling(window=window_size).mean()

plt.figure(figsize=(20,20))
for idx, col in enumerate(df.columns, 1):
    plt.subplot(df.shape[1]-4, 4, idx)
    sns.scatterplot(data=df, x=col, y='charges')
    plt.plot(df_avg[col],df['charges'])
    plt.xlabel(col)

并且,得到如下所示的图,这显然不是我想要的。

【问题讨论】:

  • 您的第一个问题是定义“具有相同的 x 坐标”的含义,因为您正在处理浮点数,所以相等性不起作用,您必须使用公差来代替。
  • @Guimoute,这个特定问题中显示的数据看起来非常明确:年份、年龄、孩子数量、性别等。因此浮点数在这里不应该成为问题。

标签: python matplotlib seaborn data-science


【解决方案1】:

如果您正在寻找一种纯粹的 matplotlib 方式来做到这一点。这是您可以采取的可能方向:

import matplotlib.pyplot as plt
import numpy as np

### Create toy dataset consisting of (500,2) points
N_points=500
rand_pts=np.random.choice(50,size=(N_points,2))

#create a dictionary with keys the unique x values and values the different y values corresponding to this unique x
rand_dict={uni:rand_pts[np.where(rand_pts[:,0]==uni),1] for uni in np.unique(rand_pts[:,0])}

#plot
plt.scatter(rand_pts[:,0],rand_pts[:,1],s=50) #plot the scatter plot
plt.plot(list(rand_dict.keys()),[np.mean(val) for val in rand_dict.values()],color='tab:orange',lw=4) #plot the mean y values for each unique x

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2021-03-13
    • 2012-05-09
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多