考虑以下数据集:
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.将“总计”列移到右端。
谁能帮我?
1条答案
按热度按时间ws51t4hk1#
实现所需结果的一个选项是将
ejes
列转换为factor
,并按所需顺序将总计列向右移动。其次,为了获得NA的灰色填充颜色,我添加了一个新的填充列,如果ig
列为NA,则将其值设置为NA,并添加group
以仍然按ejes
对堆叠条进行排序。此外,我通过scale_fill_manual
的breaks
参数从图例中删除了NA值。最后,我将"NA"
字符串转换为适当的NA,并重新编码ejes
列,因为ejes
和ig
之间存在不匹配。