R语言 如何在绘图中求出图形的坐标

gywdnpxw  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(215)

我想在一个单独的变量中获得绘制矩形的坐标,如果我调整矩形的大小,我也想改变坐标。

library(plotly)

x <- 1:50
y <- rnorm(50)

fig <- plot_ly(x = ~x, y = ~y, type = 'scatter', mode = 'lines')
fig <- config(fig,modeBarButtonsToAdd = list('drawrect'))

fig

There is a very similar question,但没有一个解决方案对我有效,那些解决方案现在一定过时了

ajsxfq5m

ajsxfq5m1#

您必须在Shiny应用程序中使用plotly_relayout事件。

library(shiny)
library(plotly)

ui <- fluidPage(
  radioButtons("plotType", "Plot Type:", choices = c("ggplotly", "plotly")),
  plotlyOutput("plot"),
  verbatimTextOutput("relayout")
)

server <- function(input, output, session) {
  
  nms <- row.names(mtcars)
  
  output$plot <- renderPlotly({
    p <- if (identical(input$plotType, "ggplotly")) {
      ggplotly(
        ggplot(mtcars, aes(x = mpg, y = wt, customdata = nms)) + geom_point()
      )
    } else {
      plot_ly(mtcars, x = ~mpg, y = ~wt, customdata = nms)
    }
    p %>% 
      layout(dragmode = "select") %>%
      config(modeBarButtonsToAdd = list("drawrect"))
  })
  
  output$relayout <- renderPrint({
    d <- event_data("plotly_relayout")
    if (is.null(d)) "Rectangle coordinates will appear here" else d
  })
  
}

shinyApp(ui, server)

相关问题