修改顶部ggplot百分比条形图上的文本标签

Modifying text labels on top ggplot percentage barplot

我正在尝试生成一个分组条形图,其中 y 轴为百分比计数,每个条形顶部的文本代表其值

我的代码如下:

  geom_bar(aes(y = (..count..)/sum(..count..) * 100), width = 0.7) + 
  labs(x = "Hours Worked 48 or more", y = "% of Employees", fill = "Hours Worked 48 or more", title = "Post-Legislation") + 
  theme_minimal() +
  scale_fill_manual(values = c("orange", "blue")) + 
  geom_text(aes(label = (..count..)/sum(..count..) * 100, y = ..prop..), stat= "count", vjust = -.5) +
  theme(legend.position = "top")

我希望 文本为白色,精确到 1dp,并放置在每个栏的顶部

我一直在尝试不同的代码,但无法得到想要的结果。

如有任何帮助,我们将不胜感激。

这是数据片段:

structure(list(year = c("2018", "2018", "2018", "2018", "2018", 
"2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", 
"2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", 
"2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", 
"2018"), hours.48 = c("Yes", "No", "No", "No", "Yes", "No", "No", 
"No", "No", "No", "No", "No", "No", "No", "Yes", "No", "No", 
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No", 
"No", "No")), row.names = c(NA, 30L), class = "data.frame")

试试这个:

library(tidyverse)
library(ggplot2)

positions = df %>% group_by(hours.48) %>% summarise(prop=n()/nrow(df)*100)

请注意,我在此处预先计算标签 = 位置。鉴于您的示例数据,没有任何小数,但如果您想沿着这条路线走下去,您可以格式化您希望在此处看到的值。就个人而言,我更喜欢预先计算我想要绘制的所有内容以分离职责。

ggplot(df, aes(x=hours.48, fill=hours.48)) +
geom_bar(aes(y = (..count..)/sum(..count..) * 100), width = 0.7) + 
  labs(x = "Hours Worked 48 or more", y = "% of Employees", fill = "Hours Worked 48 or more", title = "Post-Legislation") + 
  theme_minimal() +
  scale_fill_manual(values = c("orange", "blue")) + 
  geom_text(data=positions, aes(label = prop, y = prop), colour='white', stat= "identity", vjust = 1) +
  theme(legend.position = "top")

您还可以通过使用以下两行而不是上面相应的行来查询 positions 作为数据框而不是原始 df 来进一步简化此操作:

ggplot(positions, aes(x=hours.48, fill=hours.48)) +
  geom_bar(aes(y = prop), width = 0.7, stat='identity') + 

使用您的原始数据集和 scales 包,您可以:

library(ggplot2)
library(scales)
ggplot(df, aes(x = as.factor(hours.48), fill=as.factor(hours.48))) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    geom_text(aes(y = ((..count..)/sum(..count..)), 
                  label = scales::percent((..count..)/sum(..count..))), 
              stat = "count", vjust = 2, color="white") +
    labs(x = "Hours Worked 48 or more", y = "% of Employees", fill = "Hours Worked 48 or more", title = "Post-Legislation") + 
    theme_minimal() +
    scale_fill_manual(values = c("orange", "blue")) + 
    theme(legend.position = "top")