Home > Enterprise >  position text bar chart stacked ggplot2
position text bar chart stacked ggplot2

Time:10-23

I want to write correctly percentage in each part ?How to write the percentages well in each part? and if there is easier with plot_ly i'm okay.

Code :

mois = c("avril",   "avril",   "avril",   "avril",   "mai",     "mai",     "mai",     "mai", "juin", "juin",  "juin",   "juin",    "juillet", "juillet", "juillet", "juillet", "aout", "aout",    "aout",    "aout",    "sept",    "sept",    "sept",    "sept")

pourcentage = c(56.7, 10.0, 13.3, 20.0, 64.5,  0.0,  3.2, 32.3, 73.3,  6.7,  3.3, 16.7, 54.8, 12.9,  9.7, 22.6, 45.2, 12.9,  6.5, 35.5, 10.0 , 0.0,  3.3, 86.7)

class = c("=< -5%",    "-5 et 0 %", "0 - 5%",    ">= 5%",     "=< -5%",    "-5 et 0 %", "0 - 5%",    ">= 5%",     "=< -5%",    "-5 et 0 %", "0 - 5%",    ">= 5%",     "=< -5%",    "-5 et 0 %", "0 - 5%",    ">= 5%",     "=< -5%",    "-5 et 0 %", "0 - 5%",    ">= 5%",     "=< -5%",    "-5 et 0 %", "0 - 5%",    ">= 5%" )

table = as.data.frame(cbind(mois, pourcentage, class))

enter image description here

color <- c("green", "blue", "red", "yellow")
    


bar =  table %>%
 ggplot(mapping = aes(x = mois, 
                 y = pourcentage)) 
 geom_bar(aes(fill = class), 
     position = 'fill',  # Use position = fill to use proportions.
     stat = 'identity',
     color = "black") 
scale_y_continuous(labels = scales::percent) 
 geom_text(aes(label = paste0(pourcentage,"%")),
 position = position_fill(vjust = 0.5,
                   reverse = TRUE),
                    size = 2) 
theme_classic() 
scale_fill_manual(values = color)

ggplotly(bar)

enter image description here

CodePudding user response:

Two things:

  1. Your text positioning had the reverse = TRUE parameter. You'd need the same on the bars for them to align.
  2. Your bars had fill mapped to class, which tells ggplot to do the stacking of bars based on that variable and the way it is sorted. The text did not have fill or color specified, so the stacking would happen in order of appearance in the data. To make it stack the same way, you can specify group = class either globally (as I have done) or in aes() for the geom_text layer.

Revised:

table %>%
  ggplot(mapping = aes(x = mois, 
                       y = pourcentage, group = class)) 
  geom_bar(aes(fill = class), 
           position = position_fill(reverse = TRUE),  # Use position = fill to use proportions.
           stat = 'identity',
           color = "black") 
  scale_y_continuous(labels = scales::percent) 
  geom_text(aes(label = paste0(pourcentage,"%")),
            position = position_fill(vjust = 0.5,
                                     reverse = TRUE),
            size = 2) 
  theme_classic() 
  scale_fill_manual(values = color)

enter image description here

  • Related