使用 Matplotlib 将 R 绘图代码重写为 Python 但没有得到相同的结果

Rewriting R plot code into Python using Matplotlib but not getting same results

我试图将 R 中的绘图代码重写为 Python,但得到的结果图看起来不正确。 Python 散点图的点似乎落在一条线上。我想知道我是否在 np.random.normal 中使用了错误的函数来替换 rnorm

这是原始的 R 代码:

g <- 9.8 ##meters per second
n <- 25
tt <- seq(0,3.4,len=n) ##time in secs, t is a base function
f <- 56.67  - 0.5*g*tt^2
y <-  f + rnorm(n,sd=1)

plot(tt,y,ylab="Distance in meters",xlab="Time in seconds")
lines(tt,f,col=2)

这是 Python 中的重写尝试:

import numpy as np
import matplotlib.pyplot as plt
g = 9.8 # meters per second
n = 25 
tt = np.linspace(0, 3.4, num = n) 
f = 56.67 - 0.5 * g * tt**2
y = f + np.random.normal(n, scale=1.0)

plt.scatter(tt, y, edgecolor="black", facecolors="white")
plt.plot(tt, f, color="orange")
plt.xlabel("Time in seconds")
plt.ylabel("Distance in meters")
plt.show()

第一个是 R(期望)图:

这里是 Python 情节:

您以错误的顺序将参数传递给 np.random.normal()。第一个参数是样本的平均值,您当前给出的是 25 因此您的两条曲线在很大程度上偏移

正确的方法是将所需随机数组的大小作为最后一个参数传递size=n

y = f + np.random.normal(scale=1.0, size=n) 

其中 size 是元素的数量。 official docs 声明如下:

Parameters:
loc : float or array_like of floats Mean (“centre”) of the distribution.

scale : float or array_like of floats Standard deviation (spread or “width”) of the distribution.

size : int or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.