首页 > 解决方案 > 如何在 R 中使用 ggplotly() tooltip = "text" 显示子组的计数

问题描述

ggplotly()有谁知道我如何使用 using在工具提示中显示每组的计数grom_bar,这至少已经在视觉上显示了多少次Very Good cutColour E在 df 中一起出现?在这种情况下,我应该如何解决text美学问题?而且,我已经知道,如果我改变ggplotly(p, tooltip = "all")我会看到计数。我还检查了这个链接How to control "count" in tooltip for ggplotly withfilled bar plot in R 。但我希望有这样的灵活性,text所以我可以自定义提示。提前致谢!

library(ggplot2)
library(plotly)
data("diamonds")
p = ggplot(diamonds, aes(cut,   fill = as.factor(color), 
                   text = paste0("Cut: ", cut,"<br>Count: ", ???, "<br>Color: ",color, "<br>Count: ", ???))
      ) + 
geom_bar()

ggplotly(p, tooltip = "text")

标签: rggplot2plotlydata-visualizationggplotly

解决方案


我不太了解您真正想要展示的内容,但也许您可以在绘图之前计算值。

p <- diamonds %>% 
  count(cut, color) %>% 
  add_count(cut, wt = n, name = "total") %>% 
  ggplot(aes(x = cut, y = n, fill = as.factor(color),
             text = paste0("Cut: ", cut, "<br>Count: ", total, "<br>Color: ", color, "<br>Count:  ", n))) +
  geom_col()
ggplotly(p, tooltip = "text")

推荐阅读