【问题标题】:R shiny: renderPlot duplicates values, ggplotR闪亮:renderPlot重复值,ggplot
【发布时间】:2019-05-23 14:38:09
【问题描述】:

我对 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 中选择了某个物种,它会显示一个(非常好的)有两个物种的图?!

我没有看到我的错误,但它可能很合乎逻辑。

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

【问题讨论】:

  • 您的示例不包含 df_pheno$Number 的任何数据
  • 嗨,Jared,我不知道为什么我省略了那个,现在更正了 :-) 脚本的其余部分现在可以了 - 但仍然是同样的问题。

标签: r ggplot2 shiny reactive


【解决方案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 中的变量。

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

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 2015-12-02
    • 1970-01-01
    • 2016-12-20
    相关资源
    最近更新 更多