【问题标题】:adding sample size labels to x axis ticks for weighted survey in ggplot?将样本大小标签添加到 x 轴刻度以在 ggplot 中进行加权调查?
【发布时间】:2021-10-19 04:53:45
【问题描述】:

我有一个数据框,该数据框是通过对一系列国家及其子组的加权调查生成的

Sampling Weights Country Gender Percentage n
400 A Male 20 100
600 A Female 80 70
300 B Male 30 45
500 B Female 70 70
100 C Male 40 100
50 C Female 60 70

使用 ggplot,我想创建一个条形图,其中包含 x 轴刻度中子组的 n 个值。 x 轴是男性/女性亚组加上样本量的国家,y 轴是百分比。

重命名每个子组名称并在括号中添加样本大小太繁琐了,所以我想知道是否有更快的方法来这样做,同时还能够环绕文本。

所以

男性 (n = 100) 女性 (n = 70) A国

请记住,其中一些国家/地区名称实际上在真实数据集中很长,因此标签会变得拥挤。

【问题讨论】:

    标签: r ggplot2 survey


    【解决方案1】:
    library(dplyr); library(ggplot2)
    
    df1 %>%
      ggplot(aes(Gender, Percentage)) +
      geom_col() +
      geom_text(aes(y = 0, label = paste("n = ", n)), vjust = 1.5) +
      scale_x_discrete(name = NULL) +
      facet_wrap(~Country, strip.position = "bottom") +
      theme(strip.placement = "outside", strip.background = element_blank()) 
    

    或者:

    df1 %>%
      mutate(Gender2 = paste0(Gender, " (n = ", n, ")")) %>%
      ggplot(aes(Gender2, Percentage)) +
      geom_col() +
      scale_x_discrete(name = NULL) +
      facet_wrap(~Country, strip.position = "bottom", scales = "free_x") +
      theme(strip.placement = "outside", strip.background = element_blank()) 
    

    【讨论】:

      猜你喜欢
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      相关资源
      最近更新 更多