我使用以下代码从两个向量Model.1和Model.2中获取两个直方图。我想让R适合每个直方图的正常曲线。
library(ggplot2)
require(ggplot2)
require(reshape2)
set.seed(1)
df <- data.frame(x<-rnorm(1000,mean = 0.5, sd = 0.01),
y<-rnorm(1000,mean = 0.5, sd = 0.01))
df2 = melt(df)
ggplot(df2, aes(value, fill = variable)) + geom_histogram(position = "dodge", binwidth=0.001,colour = "black")+ scale_fill_manual(values = c('red','blue'))+
facet_wrap(~variable, nrow=2)+theme_bw()+ scale_x_continuous(breaks=seq(0.45,0.540,1/200))+ geom_vline(xintercept = 0.5, colour="black") +
stat_function(fun=dnorm)
感谢。
答案 0 :(得分:2)
有用的链接:
使用ggplot: How to add gaussian curve to histogram created with qplot?
using stat_function and facet_wrap together in GGPLOT2 in R
使用Base图形: Fitting a density curve to a histogram in R
Andreis回答了这个问题。
library(ggplot2)
data <- data.frame(V1 <- rnorm(700), V2=sample(LETTERS[1:7], 700, replace=TRUE))
ggplot(data, aes(x=V1)) +
stat_bin(aes(y=..density..)) +
stat_function(fun=dnorm) +
facet_grid(V2~.)
这就是我一直在尝试的,但它并没有真正发挥作用。 也许一个ggplot2专家可以照亮我们。 :)
ggplot(df2, aes(x = value)) +
stat_bin(aes(y =..density..)) +
stat_function(fun = dnorm) +
facet_grid(. ~ variable)
ggplot(data = df2, aes(x = value)) +
facet_wrap(~ variable) +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, colour = "blue")