如何剪辑一些 ggplot 元素而另一些则不剪辑

问题描述 投票:0回答:1

我有一个 R Shiny 应用程序,其中包含一个绘图,您可以在其中单击以留下标有该点的 x 和 y 坐标的标记。该代码用一些人工数据重现了相关部分:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput('plot', click = 'plot_click')
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    plot <- ggplot(data.frame(x = 1:10, y = 1:10, ll = -1:-10, ul = 2:11), aes(x, y)) +
      geom_ribbon(aes(ymin = ll, ymax = ul), linetype = 'dotted', fill = 'gray') +
      geom_line(color = 'blue') +
      coord_cartesian(clip = 'on', xlim = c(1, 10), ylim = c(-5, 15)) +
      scale_x_continuous(expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0)) +
      theme(plot.margin = margin(1, 1, 1, 1, 'cm'))
    
    if(!is.null(coords_round$x)){
      plot <- plot + geom_point(aes(x = coords_round$x, y = coords_round$y),
                                shape = 3, color = 'black', size = 3) +
      annotate("label", x = coords_round$x, y = coords_round$y+1.5,
               label = paste0('(', coords_round$x, ', ', coords_round$y, ')'))
    }
    plot
  })
  
  coords_round <- reactiveValues(x = NULL, y = NULL)
  
  observeEvent(input$plot_click, {
    coords_round$x <- signif(input$plot_click$x, 3)
    coords_round$y <- signif(input$plot_click$y, 3)
  })
}

shinyApp(ui, server)

我需要设置绘图的边界,因为 geom_ribbon 元素的限制太宽,但这引入了一个问题,因为当剪辑设置为“on”时,带有 x 和 y 坐标的注释也会剪辑,所以我得到看起来像这样的东西:

另一方面,如果我将剪辑设置为“关闭”,geom_ribbon 也不会剪辑:

是否可以有一个元素剪辑而另一个元素剪辑没有?

r ggplot2 shiny
1个回答
0
投票

无论如何,当您设置 y 刻度的限制时,一种选择是将用于

geom_ribbon
的值限制在限制范围内,例如使用使用
pmax
你可以这样做:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput("plot", click = "plot_click")
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    plot <- ggplot(data.frame(x = 1:10, y = 1:10, ll = -1:-10, ul = 2:11), aes(x, y)) +
      geom_ribbon(
        aes(ymin = pmax(ll, -5), ymax = ul),
        linetype = "dotted", fill = "gray"
      ) +
      geom_line(color = "blue") +
      coord_cartesian(clip = "off", xlim = c(1, 10), ylim = c(-5, 15)) +
      scale_x_continuous(expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0)) +
      theme(plot.margin = margin(1, 1, 1, 1, "cm"))

    if (!is.null(coords_round$x)) {
      plot <- plot + geom_point(aes(x = coords_round$x, y = coords_round$y),
        shape = 3, color = "black", size = 3
      ) +
        annotate("label",
          x = coords_round$x, y = coords_round$y + 1.5,
          label = paste0("(", coords_round$x, ", ", coords_round$y, ")")
        )
    }
    plot
  })

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

  observeEvent(input$plot_click, {
    coords_round$x <- signif(input$plot_click$x, 3)
    coords_round$y <- signif(input$plot_click$y, 3)
  })
}

shinyApp(ui, server)

© www.soinside.com 2019 - 2024. All rights reserved.