首页 > 解决方案 > 修改顶部ggplot百分比条形图上的文本标签

问题描述

我正在尝试生成一个分组条形图,其中 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,并放置在每个 bar 的顶部

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

任何帮助,将不胜感激。

这是数据片段:

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")

标签: rggplot2geom-bargeom-text

解决方案


试试这个:

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') + 

推荐阅读