Shiny + ggplot2 - plotOutput - zoom - 浮动geom_text位置

时间:2017-05-23 10:10:45

标签: r ggplot2 shiny

我有plotOutput。用户选择一个子区域,然后双击,然后绘图的范围(通过调用ggplot的{​​{1}})进行调整,以便图形现在放大到子区域。它工作正常:从img1到img2。

问题在于coord_cartesian标签的位置,因为它目前以绝对值(geom_text)指定,因此无法适应规模的变化。结果是一个凌乱的图形(img2)。

我尝试用x=Score - .75替换x=Score - .15;后一个表达式是double,其值取决于当前的缩放级别。 但是当我做出替换时R不喜欢它(这是我得到的错误):

Score-((ranges$x[2]-ranges$x[1])*.2)

IMG1: Unzoomed IMG2: Zoomed in and messy

完整代码(有问题的行注释掉):

Listening on http://127.0.0.1:7310
Warning: Error in : Aesthetics must be either length 1 or the same as the data (4): x, label, y
Stack trace (innermost first):
    110: check_aesthetics
    109: f
    108: l$compute_aesthetics
    107: f
    106: by_layer
    105: ggplot2::ggplot_build
    104: print.ggplot
    103: print
     92: <reactive:plotObj>
     81: plotObj
     80: origRenderFunc
     79: output$XassetOverview
      4: <Anonymous>
      3: do.call
      2: print.shiny.appobj
      1: print

1 个答案:

答案 0 :(得分:1)

原因是最初geom_text为空。所以你将null传递给ranges$x。您应该通过检查if(length(ranges$x))server = function (input, output){ # store range in a reactiveValues pair ranges <- reactiveValues(x = NULL, y = NULL) # generate the data XassetOverviewData <- reactive({ dataCrossAsset <- data.frame(c("point1", "point2", "point3"), c(50,33,45), c(49,50,53)) dataCrossAsset <- setNames(dataCrossAsset, c("Name", "Correlation", "Score")) return(dataCrossAsset) }) # generate the plot output$XassetOverview <- renderPlot({ plot <- ggplot(XassetOverviewData(), aes(x = Score, y = Correlation)) + geom_point(size = 5) + coord_cartesian(xlim = ranges$x, ylim = ranges$y) + geom_text(aes(x = Score - .15, label = Name), size = 3) if(length(ranges$x)){ plot <- plot + geom_text(aes(x = Score - ((ranges$x[2]-ranges$x[1]) *.1), label = Name), size = 3) } else{ plot <- plot + geom_text(aes(x = Score - .15, label = Name), size = 3) } plot }) # observeEvent 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 } adjustment <- ((ranges$x[2]-ranges$x[1])*.2) cat(adjustment, file = stderr()) }) } ui = basicPage(plotOutput(click = "plot_click", outputId = "XassetOverview", dblclick = "plot1_dblclick", brush = brushOpts(id = "plot1_brush", resetOnNew = TRUE) )) shinyApp(server=server, ui=ui) 的长度来检查是否已经发生了双击。

LIKE