代码之家  ›  专栏  ›  技术社区  ›  Vitalijs

为ggplot2中的每个面添加不同的次X轴

  •  3
  • Vitalijs  · 技术社区  · 7 年前

    我想给每个方面添加一个不同的辅助轴。以下是我的工作示例:

    library(ggplot2)
    library(data.table)
    
    #Create the data:
    data<-data.table(cohort=sample(c(1946,1947,1948),10000,replace=TRUE),
                     works=sample(c(0,1),10000,replace=TRUE),
                     year=sample(seq(2006,2013),10000,replace=TRUE))
    data[,age_cohort:=year-cohort]
    data[,prop_works:=mean(works),by=c("cohort","year")]
    
    #Prepare data for plotting:
    data_to_plot<-unique(data,by=c("cohort","year"))
    
    #Plot what I want:
    ggplot(data_to_plot,aes(x=age_cohort,y=prop_works))+geom_point()+geom_line()+
      facet_wrap(~ cohort)
    

    图中显示了某一特定群体中有多少人在特定年龄工作。我想添加一个二次X轴,显示不同队列的特定年龄对应的年份。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Z.Lin    6 年前

    由于您有要在数据集中使用的实际值,一个解决方法是将它们作为附加的 geom_text 层:

    ggplot(data_to_plot,
           aes(x = age_cohort, y = prop_works, label = year))+
      geom_point() +
      geom_line() +
      geom_text(aes(y = min(prop_works)),
                hjust = 1.5, angle = 90) +           # rotate to save space
      expand_limits(y = 0.44) +
      scale_x_continuous(breaks = seq(58, 70, 1)) +  # ensure x-axis breaks are at whole numbers
      scale_y_continuous(labels = scales::percent) +
      facet_wrap(~ cohort, scales = "free_x") +      # show only relevant age cohorts in each facet
      theme(panel.grid.minor.x = element_blank())    # hide minor grid lines for cleaner look
    

    你可以调整 hjust 价值 geom_text() y 价值 expand_limits() 以获得合理的外观,取决于所需输出的尺寸。

    plot

    (如果数据中缺少年份,则需要更多的数据争论,但我认为情况并非如此。)