在我的shiny
应用中,我创建了一个ggplot
图表,我通过grob
转换为ggplotGrob
。 (我之所以这样做是因为我需要摆弄基础gtable
的高度。
现在我想在输出中添加clickOpts
处理程序以允许一些交互性。现在返回的坐标位于'grid'
坐标(npc
?)中,为了使用nearPoints
,我想将它们缩放回原始坐标系。我怎么能这样做?
代码
library(shiny)
library(grid)
library(ggplot2)
ui <- fluidPage(
plotOutput("plot", click = "click"),
verbatimTextOutput("debug")
)
server <- function(input, output, session) {
output$plot <- renderPlot({
pl <- qplot(mpg, disp, data = mtcars)
grid.draw(ggplotGrob(pl))
})
output$debug <- renderPrint({
req(input$click)
cat("Coordinates in npc(?): (", input$click$x, " / ", input$click$y, ")\n", sep = "")
cat("How tot get that to the ggplot coordinates (i.e. to mpg and disp)?")
})
}
runApp(shinyApp(ui, server))
更新
通过CCurtis的评论,我稍微更新了我的代码:
library(shiny)
library(grid)
library(ggplot2)
dat <- data.frame(x = 1:10, y = 10 * (1:10), z = 1:10 + 10)
ui <- fluidPage(
fluidRow(column(width = 3, selectInput("x", "Select x-Axis:",
choices = names(dat))),
column(width = 3, radioButtons("grid", "Use Grid?",
choices = c("Yes", "No")))),
plotOutput("plot", click = clickOpts("click", FALSE)),
verbatimTextOutput("debug")
)
server <- function(input, output, session) {
getPlot <- reactive({
req(input$x)
ggplot(dat, aes_string(input$x, "y")) + geom_point() +
scale_y_continuous(breaks = dat$y) +
scale_x_continuous(breaks = dat[[input$x]])
})
output$plot <- renderPlot({
if (input$grid == "Yes") {
grid.draw(ggplotGrob(getPlot()))
} else {
getPlot()
}
})
output$debug <- renderPrint({
req(input$click)
cat("Coordinates in ?: (", input$click$x, " / ", input$click$y, ")\n",
sep = "")
pl <- getPlot()
xl <- ggplot_build(pl)$layout$panel_ranges[[1]]$x.range
yl <- ggplot_build(pl)$layout$panel_ranges[[1]]$y.range
cat("Limits of plot: x = ", xl[1], " / ", xl[2], "\ty = ",
yl[1], " / ", yl[2], "\n", sep = "")
trans <- function(x, y) y[1] + diff(y) * x
cat("Coordinates in native: (", trans(input$click$x, xl), " / ",
trans(input$click$y, yl), ")\n", sep = "")
})
}
runApp(shinyApp(ui, server))
但是,在使用代码时,我发现坐标(0/0)
和(1/1)
在情节面板的左下角和右上角显然不但是稍微外面。因此,我想知道input$click
实际报告的坐标是什么?这确实是npc
坐标,但坐标系的原点与绘图面板的原点不一致吗?
如您在示例中所见,直接使用ggplot
对象时,工作非常顺利。