gpt4 book ai didi

python - 根据斜率向 matplotlib 散点图添加一条线

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:19 24 4
gpt4 key购买 nike

我有一个从 DataFrame 构建的散点图 - 它显示了两个变量的相关性 - 长度和年龄

import matplotlib.pyplot as plt
df = DataFrame (......)
plt.title ('Fish Length vs Age')
plt.xlabel('Length')
plt.ylabel('Age (days)')
plt.scatter(df['length'],df['age'])

enter image description here

现在我想在散点图中添加一条给定斜率为 0.88 的线。我该怎么做?

附言我设法找到的所有示例都使用点而不是斜坡来画线

更新。我重新阅读了这个理论——事实证明,应该根据数据点绘制相关系数的事实是我编造的:)部分是因为我脑海中的这个图像enter image description here

但是我仍然对线 - matplotlib 的绘图功能感到困惑

最佳答案

相关系数不会给出回归线的斜率,因为您的数据处于不同的尺度。如果您想用回归线绘制散点图,我建议您在 seaborn 中使用最少的代码行来完成。

安装seaborn

pip install seaborn

代码示例:

import numpy as np
import pandas as pd
import seaborn as sns

# simulate some artificial data
# =====================================
df = pd.DataFrame(np.random.multivariate_normal([10, 100], [[100, 800], [800, 10000]], size=100), columns=['X', 'Y'])

df

# plot
# ====================================
sns.set_style('ticks')
sns.regplot(df.X, df.Y, ci=None)
sns.despine()

enter image description here

编辑:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# simulate some artificial data
# =====================================
df = pd.DataFrame(np.random.multivariate_normal([10, 100], [[100, 800], [800, 10000]], size=100), columns=['X', 'Y'])


# plot
# ==============================
fig, ax = plt.subplots()
ax.scatter(df.X, df.Y)

# need a slope and c to fix the position of line
slope = 10
c = -100

x_min, x_max = ax.get_xlim()
y_min, y_max = c, c + slope*(x_max-x_min)
ax.plot([x_min, x_max], [y_min, y_max])
ax.set_xlim([x_min, x_max])

enter image description here

关于python - 根据斜率向 matplotlib 散点图添加一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31583982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com