R Shiny:renderPlot复制值,ggplot

时间:2018-12-24 12:13:40

标签: r ggplot2 shiny reactive

我在Shiny中有一个反应性ggplot问题。

必要的软件包

library(shiny)
library(ggplot2)
library(ggthemes) 

生成数据集,其中包含无效的名称和相应的有效名称

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))

简单的用户界面

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectizeInput('validSpecies', 'Choose species', 
                     choices = df_pheno$Species, 
                     options = list(placeholder = 'select species'))
    ),   
    mainPanel(plotOutput("pheno")           
    )
  )
)

生成反应性图的服务器

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))    
  })
}

并运行它

shinyApp(ui = ui, server = server)

那我想要什么:如果您在selectizeInput中选择某个物种,那么您将生成一个仅包含该特定物种数据的图。

此脚本在做什么:如果您在selectizeInput中选择了某个物种,那么它将显示出一个具有两个物种的(非常好)图?!

虽然看不到我的错误,但这很合逻辑。

感谢您的所有帮助, 最好的祝愿, 乔纳斯(Jonas)

1 个答案:

答案 0 :(得分:1)

我认为在服务器功能的ggplot中,您应该替换此部分

ggplot(df_pheno, aes(x=Date, y= Species == input$validSpecies, fill = Number))

与此

ggplot(data = df_pheno[df_pheno$Species == input$validSpecies,], 
       aes(x = Date, y = Species, fill = Number))

也就是说,您应该将数据子集而不是映射到y的变量。

另外,请考虑将长序列: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)替换为1:52