使用ggplot R Shiny在同一图表上的动态多点

时间:2015-09-29 07:55:18

标签: r plot ggplot2 shiny

我正在开发一个闪亮的应用程序,旨在比较同一图表上的绘图,我想使用ggplot来放大我的图形。

问题是图的数量,这取决于用户的选择。 我想用线条绘制图形,这是我的(工作示例):

ui.R

shinyUI(fluidPage(   
  sidebarLayout(
    sidebarPanel(          
      fluidRow( 

        #checkboxGroupInput
        column((5), 
               checkboxGroupInput("model", 
                                  label = h3("Choix du modele"), 
                                  choices = c("1","2","3"),
                                  selected = 8)
        )            
      )         
    ),   
    mainPanel
    (
    fluidRow(
      column(width = 12, class = "well",
             h4("Brush and double-click to zoom"),
             plotOutput("plot1", height = 300,
                        dblclick = "plot1_dblclick",
                        brush = brushOpts(
                          id = "plot1_brush",
                          resetOnNew = TRUE
                        )
             )
      )
    )
    )
  )
)
)

server.R

# Here is the server part of Shiny 
library('shiny')
library(ggplot2)
library(reshape)
library(Cairo)

function(input, output) {


  ranges <- reactiveValues(x = NULL, y = NULL)

  output$plot1 <- renderPlot({

    tsPlot <- seq(from = ISOdate(2012,01,01,0,0,0), to = ISOdate(2012,01,01,23,45,0), by =60*15)
    measures <- runif(96)

    dataPlot <- data.frame(tsPlot,measures)
    list_models <- c("1","2","3")
    if(length(input$model) > 0)
    {
      nb = 0
      for(i in 1:length(list_models))
      {
        values <- runif(96)
        dataPlot<- cbind(dataPlot,values)
      }
    }
    dataPlot_melted <- melt(dataPlot,id="tsPlot")

    ggplot() + 
      geom_line(data=dataPlot_melted,aes(tsPlot,value)) +
      coord_cartesian(xlim = ranges$x, ylim = ranges$y)

  })

  # When a double-click happens, check if there's a brush on the plot.
  # If so, zoom to the brush bounds; if not, reset the zoom.
  observeEvent(input$plot1_dblclick, {
    brush <- input$plot1_brush
    if (!is.null(brush)) {
      ranges$x <- c(brush$xmin, brush$xmax)
      ranges$y <- c(brush$ymin, brush$ymax)

    } else {
      ranges$x <- NULL
      ranges$y <- NULL
    }
  })

}

如果我想绘制点,问题就解决了。我只需要使用geom_point。但是如果我想点线,所有的值都放在同一个图中。

有谁知道摆脱这种情况的伎俩?

提前致谢:)

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。它不是很漂亮,但有效:

  dataPlot <- data.frame(tsPlot,measures,rep("Measures",length(tsPlot)))
  names(dataPlot) <- c("ts","value","name")

    list_models <- c("1","2","3")
    if(length(input$model) > 0)
    {
      nb = 0
      for(i in 1:length(list_models))
      {
        values <- runif(96)
        dataPlot2<- data.frame(dataPlot,values,rep(list_models[i],length(values)))
        names(dataPlot2) <- c("ts","value","name")
        dataPlot <- rbind(dataPlot,dataPlot2)
      }
    }

    x <- ggplot(data=dataPlot, aes(x=time, y=value, group=name, colour=factor(name)))+
   geom_line(size=.25) 

这个技巧依赖于ggplot中的“​​group = name”。我们只有一列值,但我们还有一列标签(名称),可以正确分割数据。