【发布时间】:2018-01-05 14:32:26
【问题描述】:
我正在构建一个应用程序以更好地了解对数正态分布和正态分布的差异。该应用程序应使用 ggplot2 显示模拟数据(正态或对数正态)的直方图,并将正态、对数正态密度和内核密度拟合到假数据。出于某种原因,下面的应用程序不会显示 ggplot2 图表。
# Define UI for application that draws a histogram
library(shiny)
library(ggplot2)
library(stats)
library(gridExtra)
set.seed(15)
ui <- fluidPage(
# Application title
titlePanel("Curve fit with different distributions"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("mean",
"Mean value:",
min = 1,
max = 250,
value = 10)
,
sliderInput("spread",
"Standard deviation:",
min = 0,
max = 25,
step=0.1,
value = 2.5)
,
sliderInput("n",
"How many datapoints:",
min = 10,
max = 10000,
value = 2500)
,
selectInput("dist",
"Which data distribution?" ,
list("Normal"="dnorm" ,
"Lognormal"="dlnorm"
)
)),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot", height = "80%"))
)
)
# Define server logic required to draw a histogram with normal and log normal density
server <- function(input, output) {
sim_data<-reactive({
if(is.null(input$dist) |is.null(input$spread) | is.null(input$mean)) {
return(NULL)
}
mlog<-log(input$mean )
lspread <- log(input$spread)
dat <- data.frame(xn = rnorm(input$n, mean = input$mean, sd = input$spread), ln=rlnorm(input$n, meanlog =mlog , sdlog = lspread))
return(dat)
})
output$distPlot <- renderPlot({
if(is.null(sim_data()) |is.null(input$dist) ){
return(NULL)
}
# generate bins based on input$bins from ui.R
if(input$dist == "dnorm"){
hist_plot<- ggplot(sim_data(), aes(x = xn)) +
geom_histogram(aes(y =..density..),
colour = "black",
fill = "white") +
stat_function(fun = dnorm, colour ="#377EB8", args = list(mean = mymean, sd = mysd))+
stat_function(fun = dlnorm, colour ="#E41A1C", args = list(mean = mylmean, sd = mylsd))+
geom_density(colour="black")+
theme_minimal()
}
else{
hist_plot<- ggplot(sim_data(), aes(x = ln)) +
geom_histogram(aes(y =..density..),
colour = "black",
fill = "white") +
labs(title=distname) +
theme_minimal()+
stat_function(fun = dnorm, colour ="#377EB8", args = list(mean = mymean, sd = mysd))+
stat_function(fun = dlnorm, colour ="#E41A1C", args = list(mean = mylmean, sd = mylsd))+
geom_density(colour="black")+
theme_minimal()
}
if(input$dist == "dnorm"){
box_plot<- ggplot(sim_data(), aes(x="",y = xn)) +
geom_boxplot()+
theme_minimal()
}
else{
box_plot<- ggplot(sim_data(), aes(x="",y = ln)) +
geom_boxplot(
)+
theme_minimal()
}
p=grid.arrange(hist_plot+
theme_minimal(),box_plot+
theme_minimal(), ncol=1,nrow=2, heights = c(4,2))
plot(p)
})
}
# Run the application
shinyApp(ui = ui, server = server)
【问题讨论】: