带有填充颜色的密度图的ggplot直方图
ggplot histogram with density plot that is filled with color
我有下面的直方图 ggplot
library(ggplot2)
set.seed(1)
df <- data.frame(PF = 10*rnorm(1000))
ggplot(df, aes(x = PF)) +
geom_histogram(aes(y =..density..),
breaks = seq(-50, 50, by = 10),
colour = "black",
fill = "white") +
stat_function(fun = dnorm, args = list(mean = mean(df$PF), sd = sd(df$PF)))
现在我想用一些颜色填充法线密度曲线。我在下面试过没有成功
stat_function(fun = dnorm, args = list(mean = mean(df$PF), sd = sd(df$PF)), fill = 'red', alpha = 0.50)
有什么方法可以在正常密度曲线下的区域应用填充颜色?
您可以使用 non-default geom(此处:geom_ribbon
)调用 stat_function()
,并使用 [=14= 访问 stat_function
生成的 y-value ] 像这样:
## ... +
stat_function(fun = dnorm,
args = list(mean = mean(df$PF), sd = sd(df$PF)),
mapping = aes(x = PF, ymin = 0,
ymax = after_stat(y) ## see (1)
),
geom = 'ribbon',
alpha = .5, fill = 'blue'
)
(1) 关于访问 计算变量 (统计):https://ggplot2.tidyverse.org/reference/aes_eval.html
我有下面的直方图 ggplot
library(ggplot2)
set.seed(1)
df <- data.frame(PF = 10*rnorm(1000))
ggplot(df, aes(x = PF)) +
geom_histogram(aes(y =..density..),
breaks = seq(-50, 50, by = 10),
colour = "black",
fill = "white") +
stat_function(fun = dnorm, args = list(mean = mean(df$PF), sd = sd(df$PF)))
现在我想用一些颜色填充法线密度曲线。我在下面试过没有成功
stat_function(fun = dnorm, args = list(mean = mean(df$PF), sd = sd(df$PF)), fill = 'red', alpha = 0.50)
有什么方法可以在正常密度曲线下的区域应用填充颜色?
您可以使用 non-default geom(此处:geom_ribbon
)调用 stat_function()
,并使用 [=14= 访问 stat_function
生成的 y-value ] 像这样:
## ... +
stat_function(fun = dnorm,
args = list(mean = mean(df$PF), sd = sd(df$PF)),
mapping = aes(x = PF, ymin = 0,
ymax = after_stat(y) ## see (1)
),
geom = 'ribbon',
alpha = .5, fill = 'blue'
)
(1) 关于访问 计算变量 (统计):https://ggplot2.tidyverse.org/reference/aes_eval.html