簡體   English   中英

無法將正態曲線擬合到分組的直方圖

[英]Can't fit a normal curve to a grouped histogram

我正在為分配的任務而苦苦掙扎。 我們必須制作一個疊加了正常擬合的分組直方圖。 現在,我已經設法在Basic R圖,Lattice和Ggplot中獲得了分組的直方圖。 在Basic R圖中,我也可以在其中得到一條法線,但是在Lattice和Ggplot中,我似乎這樣做失敗。

這是我來自萊迪思和Ggplot的R腳本:

#Lattice:
library(lattice)
histogram(~SBP, data= DataSBP, breaks=10,
          type=c("density"), 
          groups = User, panel = function(...)panel.superpose(...,panel.groups=panel.histogram, col=c("navy","maroon3"),alpha=0.4),
          auto.key=list(columns=2,rectangles=FALSE, col=c("navy","maroon3")))
panel.mathdensity(dmath=dnorm, col="black", args=list(mean=mean(x, na.rm = TRUE), sd=sd(x, na.rm = TRUE)))

當我嘗試命令“ panel.mathdensity”時,沒有任何反應。

# Ggplot
library(ggplot2)
ggplot(DataSBP, aes(x=SBP)) + geom_histogram(aes(y=..density.., x=SBP, colour=User, fill=User),alpha=0.5, binwidth = 5, position="identity")
+ stat_function(fun = dnorm, args = list(mean = SBP.mean, sd = SBP.sd))

如果我嘗試使用stat_function命令,總是會收到錯誤消息“ SBP.mean”,這可能意味着我必須定義SBP.mean,但是如何?

我的數據是這樣的:

User SBP    
No 102    
No 116    
No 106    
...    
Yes 117    
Yes 127    
Yes 111    
...

我的圖看起來像這樣:

萊迪思的圖

圖表形式Ggplot

您在尋找這樣的東西嗎? 我無權訪問您的數據集,所以我使用了虹膜數據集

library(dplyr); library(ggplot2)

meanSe <- iris %>% 
  filter(Species == "setosa") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
meanVe <- iris %>% 
  filter(Species == "versicolor") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
meanVi <- iris %>% 
  filter(Species == "virginica") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
ggplot(iris, aes(x=Sepal.Length, color=Species, fill=Species)) +
  geom_histogram(aes(y=..density..), position="identity", binwidth=.5) + 
  stat_function(fun = dnorm, color="red", args=list(mean=meanSe$means, sd=meanSe$sd)) + 
  stat_function(fun = dnorm, color="green", args=list(mean=meanVe$means, sd=meanVe$sd)) + 
  stat_function(fun = dnorm, color="blue", args=list(mean=meanVi$means, sd=meanVi$sd)) + 
  theme_bw()

給這個 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM