ggplot转换为ggplotly不显示所有闪亮的图表

时间:2020-06-20 13:10:06

标签: r shiny ggplotly

我在下拉菜单中有3个图,使用ggplotly [从ggplot转换]“ bar”,“ area”,“ histogram”。基于选择,相应的图表将显示在“ rfp”绘图区域中(一次,我仅选择一个绘图)。但是我面临的问题是,根据选择,我无法看到前两个图表“条形图”,“区域”。根据选择,我只能查看第三张图表作为绘图区域的一部分。 [但是当我使用ggplot时,我没有遇到这个问题]

ui.r

tabPanel('Charts', plotlyOutput("rfp"))

server.r

output$rfp <- renderPlotly({


if ((input$ChartType=="Bar" )){
        SimBar <-ggplot(dataset, aes(x = fct_rev(fct_infreq(dataset[,prd])), y=..count..)) +
        geom_bar(stat="count")
        print(ggplotly(SimBar))}

if ((input$ChartType=="Area" ){
        Area <- ggplot(dataset, aes_string(x=dataset[,prd]))+
        geom_density(stat = "bin", alpha=0.5)
        print(ggplotly(Area))}

if ((input$ChartType=="Histogram" ){
        Hist <- ggplot(dataset, aes((x=dataset[,prd])))+
        geom_histogram (stat = "count")
        print(ggplotly(Hist))}
     }

1 个答案:

答案 0 :(得分:1)

任何“ renderXXX”的作用类似于一个函数:它返回其主体的最后一条语句的结果。在这里,您的最后一条语句是if(input$ChartType=="Histogram"){ ... }。如果NULL不是input$ChartType,则为"Histogram"。您可以执行以下操作:

output$rfp <- renderPlotly({
  if(input$ChartType=="Bar"){
    gg <- ggplot(dataset, aes(x = fct_rev(fct_infreq(dataset[,prd])), y=..count..)) +
      geom_bar(stat="count")
  }else if(input$ChartType=="Area"){
    gg <- ggplot(dataset, aes_string(x=dataset[,prd])) +
      geom_density(stat = "bin", alpha=0.5)
  }else if(input$ChartType=="Histogram"){
    gg <- ggplot(dataset, aes((x=dataset[,prd]))) +
      geom_histogram(stat = "count")
  }
  ggplotly(gg)
}