Shiny中Y轴使用对数转换后绘图点点击交互失效如何解决
问题原因
nearPoints 默认直接用原始数据集的坐标值匹配点击事件返回的坐标,而你给Y轴应用自定义的reverselog_trans转换后,绘图实际使用的是转换后的坐标空间,点击事件返回的y值是转换后的数值,和原始数据的plot列数值不一致,因此无法识别到点位。
修复方案
无需修改现有绘图配置,仅需要在调用nearPoints时,通过ytrans参数传入你自定义的反向对数转换函数,让nearPoints自动完成坐标转换匹配即可。
修改点
仅调整server中renderTable部分的代码:
output$data <- renderTable({ req(input$plot_click) nearPoints(pretend_data, input$plot_click, ytrans = reverselog_trans(10)) })
完整可运行代码
## Read in necessary libraries, function, and data library(shiny) library(ggplot2) library(dplyr) library(scales) reverselog_trans <- function(base = exp(1)) { trans <- function(x) -log(x, base) inv <- function(x) base^(-x) trans_new(paste0("reverselog-", format(base)), trans, inv, log_breaks(base = base), domain = c(1e-100, Inf)) } pretend_data <- tibble(data=1:5, estimate = runif(5, min = -1, max = 2), plot = c(1e-50, 2e-35, 5e-1, 1, 50)) # Define UI for application that draws a volcano plot ui <- fluidPage( # Application title titlePanel("Pretend Plot"), plotOutput("plot", click = "plot_click"), tableOutput("data") ) # Define server logic required to draw a volcano plot server <- function(input, output, session) { output$plot <- renderPlot({ ggplot(data = pretend_data, aes(x=estimate, y=plot)) + geom_vline(xintercept=c(-1, 1), linetype=3) + geom_hline(yintercept=0.01, linetype=3) + geom_point() + scale_y_continuous(trans = reverselog_trans(10)) }, res = 96) output$data <- renderTable({ req(input$plot_click) nearPoints(pretend_data, input$plot_click, ytrans = reverselog_trans(10)) }) } # Run the application shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者Madomako
相关产品推荐
相关产品推荐

