闪亮的鼠标点击ggplot2饼图

时间:2017-03-30 17:07:39

标签: r ggplot2 charts shiny pie-chart

我知道我可以通过ggplot2生成的叠加条形图获得闪亮的xy鼠标点击坐标:

data <- data.frame(pie = c(0.25,0.25,0.25,0.25))
library(ggplot2)
ui <- fluidPage(
  plotOutput('pie', click = "plot_click"),
  verbatimTextOutput('mouse')
)

server <- function(input, output) {
    output$pie <- renderPlot({
        ggplot(data, aes(x = factor(1), y = pie, fill = row.names(data))) 
              + geom_bar(stat = "identity")
})
    output$mouse <- renderPrint({
        str(input$plot_click)
    })
}

shinyApp(ui=ui, server=server) 

当我刚刚运行并点击时,我得到了这种输出,特别是一个列表,其中包含我在图中点击的相对xy坐标:

List of 7
$ x      : num 0.887
$ y      : num 0.116
$ mapping:List of 3
 ..$ x   : chr "factor(1)"
 ..$ y   : chr "pie"
 ..$ fill: chr "row.names(data)"
$ domain :List of 4
 ..$ left  : num 0.5
 ..$ right : num 1.5
 ..$ bottom: num -0.05
 ..$ top   : num 1.05
$ range  :List of 4
 ..$ left  : num 44.9
 ..$ right : num 818
 ..$ bottom: num 365
 ..$ top   : num 5.48
$ log    :List of 2
 ..$ x: NULL
 ..$ y: NULL
$ .nonce : num 0.797

但是,当我将其转换为饼图而不是以下内容时,我没有获得包含x和y的int 0元素的列表。我正在使用此代码(它只是将coord_polar(theta =“y”)添加到ggplot):

data <- data.frame(pie = c(0.25,0.25,0.25,0.25))
library(ggplot2)
ui <- fluidPage(
  plotOutput('pie', click = "plot_click"),
  verbatimTextOutput('mouse')
)

server <- function(input, output) {
    output$pie <- renderPlot({
        ggplot(data, aes(x = factor(1), y = pie, fill = row.names(data))) 
            + geom_bar(stat = "identity") 
            + coord_polar(theta = "y")
    })
    output$mouse <- renderPrint({
        str(input$plot_click)
    })
 }

shinyApp(ui=ui, server=server) 

点击情节后,这给了我这样的结果:

List of 7
$ x      : int 0
$ y      : int 0
$ mapping:List of 3
 ..$ x   : chr "factor(1)"
 ..$ y   : chr "pie"
 ..$ fill: chr "row.names(data)"
$ domain :List of 4
 ..$ left  : NULL
 ..$ right : NULL
 ..$ bottom: NULL
 ..$ top   : NULL
$ range  :List of 4
 ..$ left  : num 31.9
 ..$ right : num 818
 ..$ bottom: num 373
 ..$ top   : num 5.48
$ log    :List of 2
 ..$ x: NULL
 ..$ y: NULL
$ .nonce : num 0.964

我很想将这些鼠标事件用于绘图。有没有办法获得ggplot饼图的鼠标点击坐标?如果不可能,有没有办法使用javascript来转换我点击以绘制坐标的位置的像素坐标?或者,是否有更好的图形系统可以支持我可以在闪亮中使用的这种功能?

先谢谢!

1 个答案:

答案 0 :(得分:1)

对于这个问题,似乎不是一个简单的答案,而不是在R之外使用图形和网络编程。

我的解决方案是为html中的绘图创建一个图例,用户点击图例的一部分以获取他们选择的数据。