4

I would like to add a different secondary axis to each facet. Here is my working example:

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)

The plot shows how many people of a particular cohort work at a given age. I would like to add a secondary x axis showing which year corresponds to a particular age for different cohorts.

Vitalijs
  • 938
  • 7
  • 18
  • Take a look at: https://stackoverflow.com/questions/26917689/how-to-use-facets-with-a-dual-y-axis-ggplot. With the latest version of ggplot2 you can use something like `scale_x_continuous(sec.axis = sec_axis(~ . + 1948))`, but afaik it is not possible to have different formulas for different facets. – Thomas K May 23 '18 at 10:28
  • @ThomasK these are bad news :( – Vitalijs May 23 '18 at 10:41
  • @Vitalijs: well you can still plot them individually then merge all together. More work but still doable – Tung May 23 '18 at 12:55
  • @Tung thanks, this I considered I just have never found a good enough introduction into grobs! – Vitalijs May 23 '18 at 13:14
  • @Vitalijs: check this thread https://community.rstudio.com/t/ggplot2-no-option-for-multiple-independent-axis/8713 – Tung May 23 '18 at 15:01

1 Answers1

2

Since you have the actual values you want to use in your dataset, one work around is to plot them as an additional geom_text layer:

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

You can adjust the hjust value in geom_text() and y value in expand_limits() for a reasonable look, depending on your desired output's dimensions.

plot

(More data wrangling would be required if there are missing years in the data, but I assume that isn't the case here.)

Z.Lin
  • 28,055
  • 6
  • 54
  • 94