Kelly James
Kelly James

Reputation: 83

Plotting 2 y axis's when they you cannot scale them

I've got some data from sediment cores and would like to plot age and depth against OC%. Here is some mock data:

OC<-c(0.3,0.2,0.1,0.2,0.1,0.1,0.01,0.009)
depth<-c(0,1,2,3,4,5,6,7)
age<-c(0,5,8,12,20,30,60,100)
age<-2022-age
data<-data.frame(OC,depth,age)

ggplot(data,aes(OC,age))+
  geom_point()+
  theme_classic()+
  scale_y_continuous(limits = c(1920,2022))

ggplot(data,aes(OC,depth))+
  geom_point()+
  theme_classic()+
  scale_y_reverse()

Plotting against age gives me this: enter image description here

I'd like to add another y axis that shows depth. This isn't linear as the sediment compresses the further down you go. So there are more data points are more recent ages, although there is a sample per cm of the core:

enter image description here

Does anyone know if I can do this in ggplot?

Upvotes: 1

Views: 30

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

You can use approxfun as your transformation function to sec_axis:

ggplot(data, aes(OC, age)) +
  geom_point() +
  theme_classic() +
  scale_y_continuous(limits = c(1920, 2022),
                     sec.axis = sec_axis(approxfun(data$age, data$depth, rule=2),
                                         breaks = unique(data$depth),
                                         name = 'depth (cm)'))

enter image description here

Upvotes: 1

Related Questions