I am writing a shiny app and using ggplot to plot a density map. Unfortunately, I am not able to get ggplot to understand my input variable in the aes() section. Below is a part of the code that is problematic in my server.R:
output$mapPlot <- renderPlot({
ggplot(data=Robbery,aes(x=X.Coordinate.Code,y=Y.Coordinate.Code),environment = .e) +
stat_density2d(aes(fill=..density..,alpha=cut(..density..,breaks=c(0,input$ranged,Inf))),
geom = "raster", contour = FALSE)
})
The error output is : Error in cut.default: object 'input' not found
The input variable that I want to pass is input$ranged. I have seen the suggestion of using aes_string() instead of aes() when using a variable like this. My problem is that when I use aes_string() it is not able to understand what ..density.. is. Is there another way to get ggplot to accept the input$ranged variable other then using aes_string()?
Thank you very much.
Note: when I just print out the input$ranged variable in my app, it works fine. Here is the server.R code for just printing input$ranged:
output$mapText = renderText({
paste("the cutoff is",input$ranged)
})
Here is a little R code I've added that can be run to reproduce the problem:
library(ggplot2)
set.seed(42)
df = data.frame(matrix(rnorm(2000), nrow=1000))
df
ggplot(data= df,aes(x=X1,y=X2)) + geom_point() +
stat_density2d(aes(fill=..density..,alpha=cut(..density..,breaks=c(0,0.02,Inf))),geom = "raster", contour = FALSE)
test=0.02
ggplot(data= df,aes(x=X1,y=X2)) + geom_point() +
stat_density2d(aes(fill=..density..,alpha=cut(..density..,breaks=c(0,test,Inf))),geom = "raster", contour = FALSE)
The "test" variable is not understood by ggplot. But, if I use aes_string() instead of aes(), the ..density.. is not understood.