我需要一個直方圖來表示我的數據,但找不到一條曲線。任何人都可以請建議一個直方圖顯示頻率(而不是密度)與下面的數據曲線?花式的是首選,但不用擔心:)曲線在R中的直方圖
x <- rnorm(1000)
hist(x)
我需要一個直方圖來表示我的數據,但找不到一條曲線。任何人都可以請建議一個直方圖顯示頻率(而不是密度)與下面的數據曲線?花式的是首選,但不用擔心:)曲線在R中的直方圖
x <- rnorm(1000)
hist(x)
這裏的慢,一步一步的版本。
這是你的數據。
population_mean <- 0
population_sd <- 1
n <- 1000
x <- rnorm(n, population_mean, population_sd)
這些是一些x
繪製曲線的座標。請注意使用qnorm
從正態分佈中得到較低和較高的分位數。
population_x <- seq(
qnorm(0.001, population_mean, population_sd),
qnorm(0.999, population_mean, population_sd),
length.out = 1000
)
爲了從密度轉換爲計數,我們需要知道binwidth。如果我們自己指定,這是最簡單的。
binwidth <- 0.5
breaks <- seq(floor(min(x)), ceiling(max(x)), binwidth)
這是我們的直方圖。
hist(x, breaks)
計數曲線是正常密度乘以數據點數除以binwidth。
lines(
population_x,
n * dnorm(population_x, population_mean, population_sd) * binwidth,
col = "red"
)
讓我們再看看樣本分佈而不是人口分佈。
sample_mean <- mean(x)
sample_sd <- sd(x)
sample_x <- seq(
qnorm(0.001, sample_mean, sample_sd),
qnorm(0.999, sample_mean, sample_sd),
length.out = 1000
)
lines(
population_x,
n * dnorm(sample_x, sample_mean, sample_sd) * binwidth,
col = "blue"
)
它看起來很棒。謝謝你的時間 –
也許是這樣的...?
set.seed(1)
x <- rnorm(1000)
hist(x, las=1)
par(new=TRUE)
plot(density(x), col=2, yaxt="n", xaxt="n",
bty='n', xlab="", ylab="", main='')
axis(4, las=1)
頻率在左ÿ軸和概率(用於密度線)是在右ÿ軸被描繪。
通常你會使用密度曲線。
試試這個:
x <- rnorm(1000)
hist(x)
curve(dnorm, col = 2, add = TRUE)
直方圖看起來OK,但曲線似乎沒有工作,我想? –
哦,你需要一個直方圖來顯示頻率,而不僅僅是密度,我的錯誤。 Richie Cotton的回答是直接的。 – MartinR
http://stackoverflow.com/questions/1497539/fitting-a-density-curve-to-a-histogram-in-r –