Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add thousand comma seperator for values in ggplotly's hover option

Tags:

r

ggplot2

plotly

I have the following chart created in R using ggplot2 and plotly

library(tidyverse)
library(plotly)

data <- data.frame(Values = c(1000, 2000, 3000), Category = c('one', 'two', 'three'))

p <- data %>% 
  ggplot(aes(x = Category, y = Values)) +
  geom_bar(stat = 'identity') 

p %>% ggplotly()

Is there any way I can format the Values in the hover information to have a thousand comma seperator? So for example, the number 1000 to appear as 1 000 or 1,000?

like image 488
Tanga94 Avatar asked Oct 16 '25 04:10

Tanga94


1 Answers

Using the text aesthetic and making use of scales::number or scales::comma this could be achieved like so:

library(tidyverse)
library(plotly)

data <- data.frame(Values = c(1000, 2000, 3000), Category = c('one', 'two', 'three'))

p <- data %>% 
  ggplot(aes(x = Category, y = Values, text = paste("Values:", scales::number(Values)))) +
  geom_bar(stat = 'identity') 

p %>% ggplotly(tooltip = c("x", "text"))

enter image description here

like image 113
stefan Avatar answered Oct 18 '25 19:10

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!