Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding different secondary x axis for each facet in ggplot2

Tags:

r

ggplot2

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.

like image 676
Vitalijs Avatar asked Oct 18 '25 11:10

Vitalijs


1 Answers

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.)

like image 195
Z.Lin Avatar answered Oct 21 '25 03:10

Z.Lin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!