How do I customize the tooltip in ggplotly?

2.2k Views Asked by At

I'd like to round the values in the tooltip for ggplotly.

I have code and when you hover over a column, it shows the full value.

I checked the docs but I had a hard time finding instructions.

This is my code

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)
  

When I hover over one of the columns, it shows the value as the full number (60.2312).

I'd like to show the rounded version of that, so it shows 60 instead

1

There are 1 best solutions below

0
On

This could be achieved by mapping a formatted string on the text aesthetic, e.g. to show the score with no digits you could use paste("score:", scales::number(score, accuracy = 1)). As this adds another entry in the tooltip you have to add option tooltip = list("text", "count") to prevent the default entry for 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