英文:
how to get the coordinates of the drawn figure in plotly
问题
我想要将绘制的矩形的坐标存储在一个单独的变量中,同时如果我调整矩形的大小,也希望坐标能够随之改变。
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
这里有一个非常相似的问题,但是那些解决方案对我无效,这些解决方案可能已经过时了。
英文:
I would like to get the coordinates of the drawn rectangle in a separate variable, also I would like the coordinates to change if I resize the rectangle.
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, but none of the solutions worked for me, those solutions must be outdated by now
答案1
得分: 2
你必须在Shiny应用程序中使用plotly_relayout
事件。
库(shiny)
库(plotly)
ui <- fluidPage(
radioButtons("plotType", "绘图类型:", choices = c("ggplotly", "plotly")),
plotlyOutput("plot"),
verbatimTextOutput("relayout")
)
服务器 <- 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)) "矩形坐标将出现在这里" else d
})
}
shinyApp(ui, 服务器)
英文:
You have to use the plotly_relayout
event in a Shiny app.
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论