我想在同一图表上绘制直方图到拟合的Weibull函数。绘制直方图的代码是:
hist(data$grddia2, prob=TRUE,breaks=5)
拟合Weibull函数的代码是:(需要MASS包)
fitdistr(data$grddia2,densfun=dweibull,start=list(scale=1,shape=2))
如何在同一图表上绘制两者。我已附上数据集。
此外,任何能够提供可以实现相同功能的代码,但为每列数据创建图表的人都可获得奖励。数据集中的许多列。将所有图表放在同一页面上会很高兴。
https://www.dropbox.com/s/ra9c2kkk49vyyyc/Diameter%20Distribution.csv?dl=0
答案 0 :(得分:2)
这是代码
library("ggplot2")
library("dplyr")
library("tidyr")
library("MASS")
# Import dataset and filter the column "treeno"
# Use namespace dplyr:: explicitly because of conflict with MASS:: for function "select"
data <- read.csv("Diameter Distribution.csv") %>%
dplyr::select(-treeno)
# Function to provide the Weibull distribution for each column
# The distribution is calculated based on the estimated scale and shape parameters of the input
fitweibull <- function(column) {
x <- seq(0,7,by=0.01)
fitparam <- column %>%
unlist %>%
fitdistr(densfun=dweibull,start=list(scale=1,shape=2))
return(dweibull(x, scale=fitparam$estimate[1], shape=fitparam$estimate[2]))
}
# Apply function for each column then consolidate all in a data.frame
fitdata <-data %>%
apply(2, as.list) %>%
lapply(FUN = fitweibull) %>%
data.frame()
# Display graphs
multiplyingFactor<-10
ggplot() +
geom_histogram(data=gather(data), aes(x=value, group=key, fill=key), alpha=0.2) +
geom_line(data=gather(fitdata), aes(x=rep(seq(0,7,by=0.01),ncol(fitdata)), y=multiplyingFactor*value, group=key, color=key))
输出数字
Variant:多亏了精彩的ggplot2软件包,您还可以通过添加最后一行代码来分离图表
+ facet_wrap(~ key) + theme(legend.position = "none")
这给了你另一个数字: