Open BennettForville opened 2 years ago
Hi @BennettForville
It's not working because your function isn't returning a graph 🙃
The last line of your function is
shutdown(core45)
...but you want the last line to be that ggplot
call, so that the plot gets returned. Move the core shutdown line up, to immediately after you call fetchvars!
Also — right now things are more complex than they need to be (imho). I would suggest simplifying a bit:
output$distPlot <- renderPlot({
q10 <- input$Q10
RCP45 <- system.file("input/hector_ssp245.ini", package = "hector")
core45 <- newcore(RCP45)
setvar(core45, NA, Q10_RH(), q10, getunits(Q10_RH()))
run(core45)
result <- fetchvars(core45, 2000:2200)
shutdown(core45)
ggplot(result, aes(year, value))+
geom_point()+
facet_wrap(~variable, scales = "free") +
ggtitle(q10)
})
^^ this was the way we could have simplified our approach yesterday, @BennettForville! (I did warn you I was overcomplicating things - my fatal coding flaw 🙃 )
Just for future reference, this is one way to do this with using our function - so that we could expand to more parameters.
server <- function(input, output) {
# All non-reactive code outside of the renderPlot call, including defining the function
ssp245 <- system.file("input/hector_ssp245.ini", package = "hector")
core45 <- newcore(ssp245)
run(core45)
run_with_param <- function(core, parameter, value) {
old_value <- fetchvars(core, NA, parameter)
unit <- as.character(old_value[["units"]])
setvar(core, NA, parameter, value, unit)
reset(core)
run(core)
result <- fetchvars(core, 2000:2200)
result[["parameter_value"]] <- value
result
}
# Because our function is going to change with slider input when we call it,
# it is a reactive line of code and needs to be in its own reactive({}) call.
# This is kind of like defining a new function called plot_data, which is
# the reactive version of our run_with_param function.
plot_data <- reactive({
run_with_param(core45, Q10_RH(), input$Q10)
})
# Now, the only code inside renderPlot is our ggplot call - nothing else!
output$distPlot <- renderPlot({
# Note that we call plot_data with () like it's a function because of
# how we defined it above.
ggplot(plot_data(), aes(year, value)) +
geom_line() +
facet_wrap(~variable, scales = "free") +
ggtitle(input$Q10)
})
}
The flaw here is that I can't figure out where to shut down the core without the app returning an error. But this is all a later problem, I think! Let's keep it simple for now.
# Because calling our function is going to change with slide input,
# it is a reactive line of code and needs to be in its own reactive({}) call.
Oh!!! Interesting. Thank you @leeyap - taught me something.
@bpbond @leeyap The code works locally but when I try to run it as an app it doesn't work, no errors popped up with the most recent code but the ggplot calls just didn't do anything so a graph didn't appear.