有没有一种方法可以在R中使用ggplotly将bin范围标签添加到直方图的工具提示中? [英] Is there a way to add the bin range label into the tooltip for a histogram using ggplotly in R?

查看:77
本文介绍了有没有一种方法可以在R中使用ggplotly将bin范围标签添加到直方图的工具提示中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

data(mpg)

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

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

When you hover over the bar, I'd like for the tooltip to show the start and stop of the bin (e.g. 20-21)

推荐答案

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

Thanks for the simple plot_ly answer. For other reasons, I'd like to preserve ggplot. Here's one possible solution I came up with that extracts the histogram elements from ggbuild_plot() and plots them as a bar graph.

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"))

这篇关于有没有一种方法可以在R中使用ggplotly将bin范围标签添加到直方图的工具提示中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆