Reputation: 39
I have an issue with a reactive ggplot in Shiny.
necessary packages
library(shiny)
library(ggplot2)
library(ggthemes)
generate a dataset, it contains non-valid names, and the corresponding valid Name
df_pheno<- data.frame(Species = sample(c("Euthycerina pilosa", "Euthycerina pilosa", "Euthycerina pilosa", "Euthycerina vittithorax", "Euthycerina test")),
Number = sample(c("3", "4", "1", "1", "2")),
Date = sample(c("1", "50", "2", "30", "1")))
df_pheno$Number <- as.numeric(as.character(df_pheno$Number))
df_pheno$Date <- as.numeric(as.character(df_pheno$Date))
simple ui
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectizeInput('validSpecies', 'Choose species',
choices = df_pheno$Species,
options = list(placeholder = 'select species'))
),
mainPanel(plotOutput("pheno")
)
)
)
a server that generates reactive plot
server <- function(input, output, session) {
output$pheno <- renderPlot({
ggplot(df_pheno, aes(x=Date, y= Species == input$validSpecies, fill = Number)) + geom_tile(color="white", size=0.1)+
scale_fill_gradient(low="light grey", high="red", name="# specimens", breaks=c(0,1,2,3,4,5), labels=c(0,1,2,3,4,">=5"), limits=c(0,5))+ scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52), labels=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52), limits=c(0,53)) +
coord_equal()+
labs(x=NULL, y=NULL, title="Phenology of this species, per week")+
theme(plot.title=element_text(hjust=0.5))+
theme(axis.ticks=element_blank())+
theme(axis.text.x = element_text(size=7, angle=60)) +
theme(axis.text.y = element_text(size=7, face = "italic")) +
theme(legend.title=element_text(size=8)) +
theme(legend.text=element_text(size=8))
})
}
and run it
shinyApp(ui = ui, server = server)
So what do I want: if you select a certain species in the selectizeInput, you generate a plot with the data of ONLY that specific species.
what is this script doing: if you select a certain species in selectizeInput, it shows you a (very good) plot with two species?!
I do not see my error, although, it is probably quite logic.
Thanks for all your help, Best wishes, Jonas
Upvotes: 0
Views: 95
Reputation: 6436
I think that in your server function, in ggplot
, you should replace this part
ggplot(df_pheno, aes(x=Date, y= Species == input$validSpecies, fill = Number))
with this
ggplot(data = df_pheno[df_pheno$Species == input$validSpecies,],
aes(x = Date, y = Species, fill = Number))
That is, you should subset the data and not the variable that you map into y.
Also, consider to replace the long sequence: c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52)
with 1:52
.
Upvotes: 1