将ggplot图形复制到Shiny Application中,而不会丢失bar元素

时间:2018-04-16 16:34:12

标签: r shiny

我得到了以下Shiny应用程序,我创建了使用某些按钮过滤的图表

#Create data
dates <- seq(as.Date("2018-01-01"), as.Date("2018-05-01"), by="days")
point_duration = rnorm(n=length(dates), mean=6, sd=1)
point_duration_bench = rnorm(n=length(dates), mean=5, sd=2)
df <- data.frame(dates, point_duration, point_duration_bench)
df$week <- strftime(df$dates, format = "%V")
df$month <- strftime(df$dates, format = "%m")

current_day = Sys.Date()
current_week = strftime(current_day, format = "%V")
current_month = strftime(current_day, format = "%m")


library(shiny)
library(ggplot2)
library(plotly)

UI <- fluidPage(
  actionButton("week","Show last week"),
  actionButton("month","Show last month"),
  plotOutput("line_graph")
)
Server <- function(input, output) {

  observeEvent(input$week, {

    output$line_graph <- renderPlot({
      ggplot(df[df$week == current_week,], aes(x=dates, y=point_duration)) +
        geom_bar(stat = "identity") +
        geom_line(aes(x=dates, y = point_duration_bench), colour = "blue") + 
        geom_point() +
        labs(y="Amount of calls (#1000)",x="")
    })
  })
  observeEvent(input$month, {

    output$line_graph <- renderPlot({
      ggplot(df[df$month == current_month,], aes(x=dates, y=point_duration)) +
        geom_bar(stat = "identity") +
        geom_line(aes(x=dates, y = point_duration_bench), colour = "blue") + 
        geom_point() +
        labs(y="Amount of calls (#1000)",x="")
    })
  })

  output$line_graph <- renderPlot({
    ggplot(df, aes(x=dates, y=point_duration)) +
      geom_bar(stat = "identity") +
      geom_line(aes(x=dates, y = point_duration_bench), colour = "blue") + 
      geom_point() +
      labs(y="Amount of calls (#1000)",x="")
  })

}


shinyApp(ui = UI, server = Server)

然而,当我将情节更改为:

  output$line_graph <- renderPlotly({
   g <- ggplot(df, aes(x=dates, y=point_duration)) +
    geom_bar(stat = "identity") +
    geom_line(aes(x=dates, y = point_duration_bench), colour = "blue") + 
    geom_point() +
    labs(y="Amount of calls (#1000)",x="")

  p <- ggplotly(g)
  p
 })

我在屏幕上看到以下输出 -

enter image description here

所以堆栈条消失了。关于如何创建一个情节并保留条形元素的任何想法?

0 个答案:

没有答案