r - 修改顶部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")
解决方案
试试这个:
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') +
推荐阅读
- c# - 如何使用 C# 中的 VirusTotal.NET 库查找文件是否被病毒感染?
- mysql - 由于添加 base64 数据而旋转时无法在 TinyMCE 中保存 img url?
- python - 如何删除嵌套列表中的重复项?
- php - 检查 Laravel 迁移文件中是否存在列
- regex - 在 Ubuntu 中使用重命名递归地更改文件的前缀,(正则表达式不起作用)
- css - 如何使用边框图像制作自定义 CSS 边框?
- c++ - 有没有更简单的方法:if(num1 > num2 && num1 > num3),以获得更大的变量列表进行比较?
- python - 当图像是表格时,是否可以更改图像的部分背景颜色?
- excel - 如果存在则更新,否则插入
- ios - 如何在ios中以编程方式从后台删除应用程序