首页 > 解决方案 > 移动 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 值。

标签: rggplot2

解决方案


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)

您使用此代码制作的图


推荐阅读