使用ggplot按比例向堆叠的条形图添加标签

时间:2019-09-18 14:34:40

标签: r ggplot2

我正在尝试在堆叠的条形图中添加比例标签。我已经能够创建图表,但无法成功添加标签。我有标签,但它们居中并互相覆盖。...我知道有人问过这个问题,但是我没有找到一种可行的解决方案。

从较长的意义上讲,数据是整齐的

enter image description here

enter image description here

ggplot(data=dat) + 
  geom_bar(stat="identity", 
           mapping = aes(x=Vintage, y=OrigAmt, fill=fct_rev(Grade)),
           position = "fill") + 
  ggtitle("Proportions by Grade") +
  scale_fill_manual(values = c("grey", "gray40", "black")) + 
  guides(fill = guide_legend(reverse = TRUE, title="Grade")) + 
  scale_y_continuous(name="Proportion",label=percent_format()) +
  theme_bw() +
  theme(plot.title = element_text(hjust=0.5),
        panel.border = element_blank(), 
        panel.grid = element_blank(),
        axis.text.x = element_text(angle = 90))

2 个答案:

答案 0 :(得分:0)

尝试在geom_bar之后添加此内容

geom_text(aes(y = cumsum(OrigAmt)-OrigAmt/2, label = Grade), show.legend = F)

将y更改为y变量减去y变量一半的累加和(cumsum),将文本放置在每个小节的每个部分的中间。 您还可以添加色彩美感,甚至可以将“等级”转换为具有定义的色彩值的因素

答案 1 :(得分:0)

这似乎起作用。

enter image description here

ggplot(data = dat, 
       aes(y = freq, x = Vintage, fill = fct_rev(Grade))) +
  geom_col() +
  geom_text(aes(label = paste0(freq,"%")),
            position = position_stack(vjust = 0.5), size = 2) +
  scale_y_continuous(
    labels = dollar_format(suffix = "%", prefix = "")) +
  labs(title = "Distribution by Vintage",
       subtitle = "xxx") +
  labs(x = NULL, y = "Percentage") +
  theme_bw() +
  theme(legend.position = "bottom", 
        legend.direction = "horizontal",
        legend.title = element_blank()) +
  guides(fill = guide_legend(reverse = T)) +
  scale_fill_manual(values = c("grey", "gray40", "brown")) +
  theme(axis.text.x = element_text(angle = 90),
        axis.text.x.bottom = element_text(vjust = 0.5))

但是,我想更改字体颜色,但看不到能够成功完成。

例如,我希望标签字体为BOLD,A和B的字体为WHITE,C的字体为BLACK。谢谢!

enter image description here