首页 > 解决方案 > 如何在 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

标签: rggplot2ggplotly

解决方案


这可以通过在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"))

在此处输入图像描述


推荐阅读