【问题标题】:Click to get coordinates from multiple histogram in shiny单击以从闪亮的多个直方图中获取坐标
【发布时间】:2016-02-18 07:28:40
【问题描述】:

我们如何在闪亮中获得多个直方图的交互坐标(x 和 y)。我试过这段代码

#server.R
library(xts)  
shinyServer(function(input, output,session) {
output$info <- renderText({
    paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
  })


output$plot<- renderPlot({ 
set.seed(3)
Ex <- xts(1:100, Sys.Date()+1:100)
df = data.frame(Ex,matrix(rnorm(100*3,mean=123,sd=3), nrow=100))
df<-df[,-1]
par(mfrow = c(2,2))
for(i in names(df)){
 hist(df[[i]] , main=i,xlab="x",freq=TRUE,label=TRUE,plot = TRUE)  
}

})
})

ui.R

#ui.r
mainPanel(

      tabsetPanel(type="tab",tabPanel("plot", plotOutput("plot",click = "plot_click"), verbatimTextOutput("info"))         

  )

上面代码的问题是我得到了像这样的整个情节的随机坐标

x=124.632301932263
y=20.4921068342051

相反,我想获取各个图的坐标及其对应的值。例如,如果我单击 X1 图表中的任何位置,我应该得到该图表的 x 和 y 坐标。我该怎么做?

【问题讨论】:

    标签: r plot shiny interactive


    【解决方案1】:

    我本来想说这是因为点击是由绘图的像素而不是数据控制的,但事实证明我错了here

    请注意,x 和 y 坐标被缩放到数据,而不是简单的像素坐标。这使得使用这些值来选择或过滤数据变得很容易。

    我会诚实地猜测,在图形设备中,Shiny 无法区分各个图之间的区别,解决方案是为每个图创建单独的设备:

    ui.R

    library(shiny)
    shinyUI(
      tabsetPanel(type="tab",
                  tabPanel("plot", 
                           uiOutput("coords"),
                           uiOutput("plots")
                           )
                  )
    )
    

    server.R

    library(xts)  
    set.seed(3)
    
    Ex <- xts(1:100, Sys.Date() + 1:100)
    df <- data.frame(Ex, matrix(rnorm(100*3, mean = 123, sd = 3), nrow = 100))
    cn <- colnames(df)
    df <- df[, cn[cn != "Ex"]]
    
    n_seq <- seq(ncol(df))
    shinyServer(function(input, output, session) {
    
      output$plots <- renderUI({
        plot_output_list <- lapply(n_seq, function(i) {
          plotOutput(paste0("plot", i), click = paste0("plot_click", i),
                     height = 250, width = 300)
        })
      })
    
      for (i in n_seq) {
        output[[paste0("plot", i)]] <- renderPlot({
          hist(df[[i]] , main = i, xlab = "x", freq = TRUE, label = TRUE)
        })
      }
    
      output$coords <- renderUI({
        coords_output_list <- lapply(n_seq, function(i) {
          renderText({
            set <- input[[paste0("plot_click", i)]]
            paste0("Plot ", i, ": x=", set$x, "\ny=", set$y)
          })
        })
      })
    })
    

    【讨论】:

    • 感谢您的代码,但您能告诉我这里发生了什么lapply(n_seq, function(i) { renderText({ set &lt;- input[[paste0("plot_click", i)]]
    • 由于每个图的点击被建立为input$plot_click&lt;i&gt;,我们使用input 列表的命名条目来获取每个图的点击。例如x &lt;- list(plot_click1 = list(x = 1, y = 2)); x[["plot_click1"]];
    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2017-05-30
    • 2021-01-06
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    相关资源
    最近更新 更多