在 R 中向堆栈条形图添加文本时出现问题

问题描述 投票:0回答:1

我正在尝试排列堆叠条形图,并在每个堆叠上显示百分比。 我提到了以下内容,但我在 3 个方面有疑问,我无法将代码与我的场景联系起来。 向百分比堆叠条形图 ggplot2 添加标签

问题1:注释的文字没有正确居中

问题2:我对一个实例有相同的百分比贡献,我需要按照图例中从左到右出现的顺序排列它(我已经实现了这一点)。对于其余情况,我需要按贡献顺序排列堆栈(按贡献排序)

问题3:某些情况下贡献率为0%。我不想显示0%

请查看代码和所附图片,以了解代码当前阶段的情况:

dput(df)
structure(list(QT = c("BMI", "BMI", "BMI", "BMI", "BMI", "WHR", 
"WHR", "WHR", "WHR", "WHR", "BF", "BF", "BF", "BF", "BF", "WC", 
"WC", "WC", "WC", "WC"), E = c("HD", "NS", "PA", "PALC", "SMK", 
"HD", "NS", "PA", "PALC", "SMK", "HD", "NS", "PA", "PALC", "SMK", 
"HD", "NS", "PA", "PALC", "SMK"), Contribution = c(21.73913043, 
0, 21.73913043, 34.7826087, 21.73913043, 24.13793103, 24.13793103, 
20.68965517, 13.79310345, 17.24137931, 16.66666667, 16.66666667, 
20, 20, 26.66666667, 20, 20, 20, 20, 20)), row.names = c(NA, 
20L), class = "data.frame")

library(ggplot2)

ggplot(df, aes(x = Contribution, y = QT,  fill = E)) +
  geom_col(size=0.5, color="black", 
           position = position_fill(reverse = TRUE)) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()+
  theme(axis.text=element_text(size=12, colour = "black"),
        axis.title = element_text(size=13),
        axis.text.x = element_blank(),
         legend.text = element_text(size=12))+
  geom_text(aes(label = paste0(round(Contribution), "%")),
            position = position_fill(vjust = 0.5))

r ggplot2 label percentage stacked-bar-chart
1个回答
0
投票

当您使用

reverse=TRUE
反转条形的顺序时,您必须对标签执行相同的操作,以使它们与条形对齐。

要去掉零的标签,您可以使用

ifelse

最后,要根据

Contribution
对每个堆栈进行排序,您可以使用我通过重新排列数据并使用
forcats::fct_inorder
创建的辅助列。然后可以将该辅助列映射到
group
aes。

library(ggplot2)
library(dplyr, warn = FALSE)


df |> 
  arrange(QT, desc(Contribution)) |> 
  mutate(
    group = forcats::fct_inorder(paste(QT, E, sep = "."))
  ) |> 
  ggplot(aes(x = Contribution, y = QT, fill = E, group = group)) +
  geom_col(
    size = 0.5, color = "black",
    position = position_fill(reverse = TRUE)
  ) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal() +
  theme(
    axis.text = element_text(size = 12, colour = "black"),
    axis.title = element_text(size = 13),
    axis.text.x = element_blank(),
    legend.text = element_text(size = 12)
  ) +
  geom_text(
    aes(label = ifelse(
      Contribution > 0,
      paste0(round(Contribution), "%"),
      ""
    )),
    position = position_fill(vjust = 0.5, reverse = TRUE)
  )

© www.soinside.com 2019 - 2024. All rights reserved.