位置文本条形图堆叠ggplot2

position text bar chart stacked ggplot2

我想把每个部分的百分比写正确?如何把每个部分的百分比写好?如果 plot_ly 更容易,我没问题。

代码:

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))

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)

两件事:

  1. 您的文本定位有 reverse = TRUE 参数。您需要在条上使用相同的条才能使它们对齐。
  2. 您的条形已填充映射到 class,这告诉 ggplot 根据该变量及其排序方式对条形进行堆叠。文本没有指定填充或颜色,因此堆叠将按数据中出现的顺序发生。为了使其以相同的方式堆叠,您可以全局指定 group = class(正如我所做的)或在 aes() 中指定 geom_text 层。

修订:

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)