2017-09-25 210 views
0

我使用Shiny和ggplot2作为交互式图形。我还使用“plot1_click”获取x和y位置。闪亮的交互式图形显示行名称

output$selected <- renderText({ 
paste0("Value=", input$plot1_click$x, "\n", 
     "Names=", input$plot1_click$y) }) #how to get names??? 

这是服务器代码的一部分。这里我想要的是,我不想打印“y”坐标,而是打印用y轴书写的相应名称。有没有任何可能的方式呢?

+0

这是一个解决方法,但假设您用来绘制的数据框包含x和y坐标,您可以使用类似'“Names =”,data $ name [data $ x == input $ plot1_click $ x&data $ y == input $ plot1_click $ y]' – KGee

回答

0

据我所知,在plotOutput中不支持点击点。点击事件只会返回点击位置的坐标。然而,这些坐标可以用来计算出最近的点。

This shiny app来自闪亮的画廊页面使用功能shiny::nearPoints正是这样做。这是一个简单的例子。

library(shiny) 
library(ggplot2) 

shinyApp(
    fluidPage(
    plotOutput("plot", click = "plot_click"), 
    verbatimTextOutput('print') 
), 
    server = function(input, output, session){ 
    output$plot <- renderPlot({ggplot(mtcars, aes(wt, mpg)) + geom_point()}) 
    output$print = renderPrint({ 
     nearPoints(
     mtcars,    # the plotting data 
     input$plot_click, # input variable to get the x/y coordinates from 
     maxpoints = 1,  # only show the single nearest point 
     threshold = 1000 # basically a search radius. set this big enough 
          # to show at least one point per click 
    ) 
    }) 
    } 
) 

verbatimTextOutput向您显示点击位置的最近点。请注意0​​只适用于像这样的ggplots。但是帮助页面表明还有一种方法可以在基本图形中使用它。