如何在ggplotly中自定义工具提示?

时间:2020-10-25 01:23:30

标签: r ggplot2 ggplotly

我想将工具提示中的值四舍五入为ggplotly。

我有代码,当您将鼠标悬停在列上时,它会显示完整的值。

我检查了文档,但很难找到说明。

这是我的代码

library(fpp)
library(plotly)
library(tidyverse)

gg <-
    credit %>% 
        ggplot(aes(score)) +
        geom_histogram(fill = "lightblue") +
        theme_ipsum_rc(grid = "XY") +   
      labs(title = paste0("Histogram: "),
           x = "")

ggplotly(gg)
  

当我将鼠标悬停在其中一列上时,它会将值显示为整数(60.2312)。

我想显示该内容的四舍五入,所以显示为60

1 个答案:

答案 0 :(得分:1)

这可以通过将格式化后的字符串映射到text美学上来实现,例如要显示没有数字的score,可以使用paste("score:", scales::number(score, accuracy = 1))。由于这会在工具提示中添加另一个条目,因此您必须添加选项tooltip = list("text", "count")来阻止score的默认条目:

library(fpp)
library(plotly)

gg <-
  credit %>% 
  ggplot(aes(score)) +
  geom_histogram(aes(text = paste("score:", scales::number(score, accuracy = 1))), fill = "lightblue") +
  labs(title = paste0("Histogram: "),
       x = "")

ggplotly(gg, tooltip = list("text", "count"))

enter image description here