stat_function不在过渡状态上过渡

时间:2020-07-25 18:12:50

标签: r

我正在尝试使用ggplot2编写自己的中心极限定理演示,而无法获取stat_function来显示变化的正态分布。

下面是我的代码,我希望stat_function中的正态分布能够在不同状态之间转换;具体来说,我希望它能够更改标准偏差以与数据集中的每个值相对应。任何帮助将不胜感激。

#library defs

library(gganimate)
library(ggplot2)
library(transformr)

#initialization for distribution, rolls, and vectors

k = 2

meanr = 1/k

sdr = 1/k

br = sdr/10

rolls <- 200

avg <- 1

dataset <- 1

s <- 1

#loop through to create vectors of sample statistics from 200 samples of size i

#avg is sample average, s is standard deviations of sample means, and dataset is the indexes to run the transition states

for (i in c(1:40)){

  for (j in 1:rolls){

    avg <- c(avg,mean(rexp(i,k)))

  }

  dataset <- c(dataset, rep(i,rolls))

  s <- c(s,rep(sdr/sqrt(i),rolls))

}


#remove initialized vector information as it was only created to start loops

avg <- avg[-1]

rn <- rn[-1]

dataset <- dataset[-1]

s <- s[-1]


#dataframe 

a <- data.frame(avgf=avg, rnf = rn,datasetf = dataset,sf = s)

#plot histogram, density function, and normal distribution

ggplot(a,aes(x=avg,y=s))+

  geom_histogram(aes(y = ..density..), binwidth = br,fill='beige',col='black')+

  geom_line(aes(y = ..density..,colour = 'Empirical'),lwd=2, stat = 'density') + 

  stat_function(fun = dnorm, aes(colour = 'Normal', y = s),lwd=2,args=list(mean=meanr,sd = mean(s)))+
  
  scale_y_continuous(labels = scales::percent_format()) +

  scale_color_discrete(name = "Densities", labels = c("Empirical", "Normal"))+

  labs(x = 'Sample Average',title = 'Sample Size: {closest_state}')+

  transition_states(dataset,4,4)+ view_follow(fixed_x = TRUE)

1 个答案:

答案 0 :(得分:3)

我认为这里很难使用SocialMediaService.Twitter,因为您传递的stat_function函数包含分组变量(dnorm)。没有方法表明您希望按mean(s)列对s进行分组,并且dataset函数不会过滤整个数据帧。您可以使用transition_states来过滤整个数据帧,但这很麻烦。

仅需在输入数据框中添加transition_filter并将其绘制为一条线就没什么工作了,特别是因为可以大大简化其余代码。这是一个完全可复制的示例:

dnorm

enter image description here