How to control “count” in tooltip for ggplotly with filled bar plot in R

浪尽此生 提交于 2021-02-11 18:01:05

问题


Thanks in advance for any advice you can offer! I'm hoping to be able to relabel "count" in the tooltip for a public facing interactive plot.

Here's a reproducible example:

library(plotly)
df <- data.frame(cat=c(rep("A", 5), rep("B", 7), rep("C", 10)),
                 time=c(rep("Time1", 3), rep("Time2", 13), rep("Time3", 6)))
ggplotly(ggplot(df, aes(x=time, fill=cat)) + geom_bar(position = "fill"))

I know I can control the time and category labels in the tooltip with text=paste("Category:", cat, "Time:" time), but can't seem to figure out how to give the count a more aesthetic titling.

Thanks for your time!


回答1:


Perhaps there's an easier solution, but you can do:

library(plotly)
df <- data.frame(cat=c(rep("A", 5), rep("B", 7), rep("C", 10)),
                 time=c(rep("Time1", 3), rep("Time2", 13), rep("Time3", 6)))
gg <- ggplotly(ggplot(df, aes(x=time, fill=cat)) + geom_bar(position = "fill"))
ggg <- plotly_build(gg)
for(i in 1:length(ggg$x$data)){
  text <- ggg$x$data[[i]]$text
  text <- gsub("count:", "Count:", text)
  text <- gsub("time:", "Time:", text)
  text <- gsub("cat:", "Cat:", text)
  ggg$x$data[[i]]$text <- text
}
ggg


来源:https://stackoverflow.com/questions/54505903/how-to-control-count-in-tooltip-for-ggplotly-with-filled-bar-plot-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!