Home > Enterprise >  Thousand separator in ggplotly
Thousand separator in ggplotly

Time:01-20

I am working on an R shiny application, I have an interactive chart in ggplotly. I would like space as a thousand separators, I have a code that is not really working.

Here's my code:

mrg <- list(l=10, r=10, b=10, t=100, pad=1)
      
        output$sortie3_evo <- renderPlotly({
          g <- ggplot(filtered_data_evo(), aes(x=Année.Scolaire, y= Nombre.élèves, fill=Secteur,label = format(as.numeric(..y..), nsmall=0, big.mark=" "))) 
          stat_summary(fun = sum, geom = "bar", position = position_dodge(0.9)) 
            theme(axis.text.x = element_text(angle=25, hjust=1)) 
            facet_wrap(~ NiveauLV, ncol = 2)  
            xlab("")

            
g <- ggplotly(g) %>%
              layout(margin = mrg)

          })

It gives me the following result:

enter image description here

The last line of the hover shows the correct thing, but I don't understand why it also shows the code. If anyone has a solution?

Here's a part of my data using dput():

structure(list(Année.Scolaire = c("2018-2019", "2018-2019", "2018-2019", 
"2018-2019", "2018-2019", "2018-2019", "2018-2019", "2018-2019", 
"2018-2019", "2018-2019"), Secteur = structure(c(2L, 2L, 2L, 
2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("PUBLIC", "PRIVE SOUS CONTRAT"
), class = "factor"), Département = c("ARDECHE", "ARDECHE", "HAUTE SAVOIE", 
"SAVOIE", "HAUTE SAVOIE", "HAUTE SAVOIE", "ISERE", "ISERE", "ISERE", 
"SAVOIE"), Cycle = c("Cycle 2", "Cycle 3", "Cycle 2", "Cycle 3", 
"Cycle 1", "Cycle 3", "Cycle 1", "Cycle 2", "Cycle 3", "Cycle 1"
), LV = c("Allemand LV1", "Allemand LV1", "Allemand LV1", "Allemand LV1", 
"Allemand LV1", "Allemand LV1", "Allemand LV1", "Allemand LV1", 
"Allemand LV1", "Allemand LV1"), Nombre.élèves = c(6, 6, 6, 324, 
66, 3, 21, 258, 18, 204), NiveauLV = c("LV1", "LV1", "LV1", "LV1", 
"LV1", "LV1", "LV1", "LV1", "LV1", "LV1"), LV_recode = c("Allemand", 
"Allemand", "Allemand", "Allemand", "Allemand", "Allemand", "Allemand", 
"Allemand", "Allemand", "Allemand")), row.names = c(NA, 10L), class = "data.frame")

Thank you in advance.

CodePudding user response:

You should use the text aesthetic and you could create a label hover text using paste like this:

mrg <- list(l=10, r=10, b=10, t=100, pad=1)
library(ggplot2)
library(plotly)
g <- ggplot(filtered_data_evo, aes(x=Année.Scolaire, y= Nombre.élèves, fill=Secteur,text = paste("label:", format(after_stat(y), big.mark=" ")))) 
    stat_summary(fun = sum, geom = "bar", position = position_dodge(0.9)) 
    theme(axis.text.x = element_text(angle=25, hjust=1)) 
    facet_wrap(~ NiveauLV, ncol = 2)  
    xlab("")

g <- ggplotly(g) %>%
    layout(margin = mrg)
g

Created on 2023-01-20 with reprex v2.0.2


Edit

To select certain aes in your hover text, you could use tooltip with the right aesthetics like this:

g <- ggplotly(g, tooltip = c("x", "fill", "text")) %>%
    layout(margin = mrg) 
g
  • Related