R语言 根据每个堆栈的值标签更改ggplot2中堆栈条形图的颜色

8nuwlpux  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(111)

考虑以下数据集:

institucion <- data.frame( 
               inst = c(rep("Inst1", 6), rep("Inst2", 6), rep("Inst3", 6), rep("Inst4", 6), rep("Inst5", 6)), 
               ejes = rep(c("total", "eje 1", "eje 2", "eje 3", "eje 4", "eje 5"), 5), 
               ig = c(1, "NA", "NA", "NA", "NA", "Total: 1", 1, 2, "NA", 4, 5,  "Total: 12", 1 , 2, 3, "NA", 5,  "Total: 11",
                      1, "NA", "NA", 4, 5, "Total: 10", 1, "NA", 3, 4, 5, "Total: 13"),   
               peso = rep(100/6, 30) 
               )

使用它可以创建以下ggplot图表:

plot6 <- ggplot(institucion, aes(x = inst, y = peso, fill = ejes, label = ig)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  geom_text(aes(label = ig),
            position = position_stack(vjust = 0.5)) +
  scale_fill_manual(values = c("white", "blue", "red", "darkgreen", "pink", "purple", "green", "gray")) +
  theme(legend.title = element_blank(),
        rect = element_blank())

结果是这样的:

我想做两件事:
1.将值为“NA”的所有堆栈设置为灰色。
1.将“总计”列移到右端。
谁能帮我?

ws51t4hk

ws51t4hk1#

实现所需结果的一个选项是将ejes列转换为factor,并按所需顺序将总计列向右移动。其次,为了获得NA的灰色填充颜色,我添加了一个新的填充列,如果ig列为NA,则将其值设置为NA,并添加group以仍然按ejes对堆叠条进行排序。此外,我通过scale_fill_manualbreaks参数从图例中删除了NA值。最后,我将"NA"字符串转换为适当的NA,并重新编码ejes列,因为ejesig之间存在不匹配。

library(ggplot2)

institucion$ig[institucion$ig == "NA"] <- NA_character_
institucion$ejes <- dplyr::case_match(
  institucion$ejes,
  "total" ~ "eje 5",
  "eje 5" ~ "total",
  .default = institucion$ejes
)
institucion$ejes <- factor(institucion$ejes, levels = rev(c(paste("eje", 1:5), "total")))
institucion$fill <- institucion$ejes
institucion$fill[is.na(institucion$ig)] <- NA_character_

ggplot(institucion, aes(x = peso, y = inst, fill = fill, label = ig, group = ejes)) +
  geom_col() +
  geom_text(aes(label = ig),
    position = position_stack(vjust = 0.5)
  ) +
  scale_fill_manual(
    breaks = function(x) x[!is.na(x)],
    values = c("white", "blue", "red", "darkgreen", "pink", "purple", "green", "gray")
  ) +
  theme(
    legend.title = element_blank(),
    rect = element_blank()
  )

相关问题