有没有办法在 R 中使用 ggplotly 将 bin 范围标签添加到直方图的工具提示中?

Is there a way to add the bin range label into the tooltip for a histogram using ggplotly in R?

library(tidyverse)
library(ggplot2)
library(plotly)

data(mpg)

ggplotly(
mpg %>% 
  ggplot(aes(x=hwy)) +
  geom_histogram(), 
tooltip = ("all"))

当您将鼠标悬停在栏上时,我希望工具提示显示垃圾箱的开始和停止(例如 20-21)

如果不强制使用 ggplot2,更简单的解决方法是使用基本直方图:

plot_ly(x = mpg$hwy, type = "histogram")

感谢简单的 plot_ly 回答。出于其他原因,我想保留 ggplot。这是我想出的一种可能的解决方案,它从 ggbuild_plot() 中提取直方图元素并将它们绘制为条形图。

ggplotly(
ggplot_build(
  mpg %>% 
    ggplot(aes(x=hwy)) +
    geom_histogram()
)$data[[1]] %>% 
  ggplot(aes(x=factor(x), y = count, text = paste0("range: ",round(xmin, 1), " - ", round(xmax,1)))) + 
  geom_bar(stat="identity") + 
  theme(axis.text.x = element_blank()),
tooltip = c("text"))

我 运行 解决了这个问题,但还需要用 bin 运行ges 标记 x 轴,所以我以你的答案为基础(太棒了!)

我将其分为三个步骤:使用 ggplot 创建第一个生成 bin 运行ges 的直方图,再次使用 ggplot 创建第二个使用这些 运行ges 作为标签的直方图,然后使用 plotly 使其具有交互性。

这是一个应该可以为其他用例定制的代表。一旦你掌握了要点,你就可以抛弃中间变量,运行 使用管道一次完成整个事情。

library(tidyverse)
library(plotly)

# step 1: create a ggplot histogram, extract the internal data
plot_step1 <- ggplot_build(
  mpg %>% 
    ggplot() + 
    geom_histogram(aes(x=hwy),
                   bins = 11 # set histogram parameters here
    )
)$data[[1]]

# step 2: create a new plot, using the derived xmin and xmax values from the 
# first plot, and set the labels and axes
plot_step2 <- plot_step1 %>% {
  ggplot(data = .,
         aes(x=factor(x), 
             y = count, 
             text = sprintf("Count: %d\nRange (MPG): %.1f-%.1f", y, round(xmin,1), round(xmax,1)))) + 
    scale_x_discrete(labels = sprintf("%.1f-%.1f", .$xmin, .$xmax)) + 
    geom_bar(stat="identity", 
             width = 1) + 
    labs(title = "Histogram: Highway Miles per Gallon",
         x = "MPG",
         y = "Count") +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 45 ))
}

# step 3: make this new plot interactive
plotly::ggplotly(plot_step2, tooltip = c("text"))

使用库(ggiraph)的解决方案:

library(tidyverse)
library(ggplot2)
library(ggiraph)

p1 <- mpg %>% 
  ggplot(., aes(x=hwy)) +
  geom_histogram_interactive(bins = 20, aes(tooltip =  paste0("[",round(..xmin..,2),",",round(..xmax..,2),"] count: ",..count..)))

ggiraph(ggobj = p1)

Example