r - 移动 geom_label 的框,使它们不重叠
问题描述
我正在尝试绘制一个人口金字塔,每个栏前面都有一个文本框(根据性别和年龄)
我的数据集如下所示:
plotstack <- structure(list(`Grupos de edad` = c(
"0 a 14", "0 a 14", "0 a 14",
"0 a 14", "0 a 14", "0 a 14", "0 a 14", "0 a 14", "15 a 29",
"15 a 29"
), Depto = c(
"Antioquia", "Atlántico", "Bogotá", "Valle del Cauca",
"Antioquia", "Atlántico", "Bogotá", "Valle del Cauca", "Antioquia",
"Atlántico"
), variable = c(
"Hombres", "Hombres", "Hombres", "Hombres",
"Mujeres", "Mujeres", "Mujeres", "Mujeres", "Hombres", "Hombres"
), total_edad = c(
721865L, 345326L, 747582L, 528768L, -689789L,
-332823L, -719228L, -513970L, 845150L, 348966L
), freq_total = c(
10.8,
12.7, 9.65, 11.7, -10.3, -12.2, -9.29, -11.3, 12.7, 12.8
), n = c(
6677930L,
2722128L, 7743955L, 4532152L, 6677930L, 2722128L, 7743955L, 4532152L,
6677930L, 2722128L
)), row.names = c(NA, -10L), class = "data.frame")
我用来绘制的代码是
library(ggplot2)
library(dplyr)
plotstack%>%
ggplot(plotstack,mapping = aes(x =freq_total/100,
y = `Grupos de edad`, fill = variable)) +
geom_col() +
scale_x_continuous(labels =abs
, limits = max(edadesplot$freq_total/100) * c(-1,1)) +
labs(x = "Porcentaje de población")+labs(title='Nacional')+
theme(legend.title = element_blank())+
geom_label(aes(label = paste(abs(freq_total)," %", sep=""), group = factor(variable)),
fill='white', colour = "black",
position= position_dodge(0),
size = 3)+
scale_fill_brewer(palette = "Set1") +
theme_bw()+theme(legend.title = element_blank())+ facet_grid(. ~ Depto)
如您所见,当条形太短时,框会重叠,因为它们没有足够的空间,我想知道如何移动它们以使它们不重叠,也许将所有框放在同一位置x 值。
解决方案
ggrepel
是为此而生的。
library(ggrepel)
library(ggplot2)
library(dplyr)
plotstack%>%
ggplot(plotstack,mapping = aes(x =freq_total/100,
y = `Grupos de edad`, fill = variable)) +
geom_col()+
labs(x = "Porcentaje de población")+labs(title='Nacional')+
theme(legend.title = element_blank())+
ggrepel::geom_label_repel(aes(label = paste(abs(freq_total)," %", sep=""), group = factor(variable)),
fill='white', colour = "black",
position= position_dodge(0),
size = 3)+
scale_fill_brewer(palette = "Set1") +
theme_bw()+theme(legend.title = element_blank())+ facet_grid(. ~ Depto)
推荐阅读
- sql-server - 如何使用 symfony odm 连接 MSSQL
- floating-point - 64位十六进制转换为十进制
- spring - Flyway 还原迁移验证
- php - Spatie-laravel-analytics 包 ga:users 不准确
- python - Python:为简单的 OLS 循环变量
- r - R - 如何在保持其他列静止的同时对单个列进行热编码?
- python - Python 正则表达式 sub()
- oracle - 从 apex_item.text 获取价值
- android - 如何获取 firebase 数据库元素的推送 ID 以便在 listView 中显示它
- sql - 从循环输出 Oracle SQL 创建表