如何自定义ggplotly提示框内容使其与图表x、y轴标签对应
可以实现,你之前的操作没有生效是因为ggplot2非标准评估的映射写法有问题,同时提示框参数的调用位置不对,以下是可直接运行的修改方案:
- 修正aes的变量映射写法,使用
.data[[input$dataColumn]]调用shiny动态传入的变量,避免语法歧义 - 在geom_histogram的aes中新增text参数,直接按照你需要的格式拼接提示框内容
- 在ggplotly函数中指定tooltip参数为"text",仅展示自定义的提示框文本
修改后完整代码:
--- title: "Title" output: html_document runtime: shiny --- {r, echo = FALSE} library(epiDisplay) library(ggplot2) library(dplyr) library(hrbrthemes) library(plotly) dataSet <- mtcars selectInput(inputId = 'dataColumn', label = '请选择要查看的变量', choices = names(dataSet)) sliderInput(inputId = 'bin', label = '请选择分箱数量', min = 5, max = 50, value = 30) renderPlotly({ cur_col <- input$dataColumn p <- ggplot(dataSet, aes(x = .data[[cur_col]])) + geom_histogram(bins = input$bin, fill = "#3379b7", color = "#3379b7", alpha = 0.9, aes(text = paste0( "Frequency: ", after_stat(count), "\n", cur_col, ": ", round(after_stat(x), 5) ))) + xlab(cur_col) + ylab("Frequency") + theme_ipsum() ggplotly(p, tooltip = "text") })
上述代码运行后,不管切换什么变量,提示框的标签都会和x、y轴的标签完全匹配,数值精度可以通过调整round()函数的第二个参数修改,不需要精度控制直接删除round()即可。
内容的提问来源于stack exchange,提问作者Kayla
相关产品推荐
相关产品推荐

