Home > Software engineering >  plot two x axis on one ggplot
plot two x axis on one ggplot

Time:06-15

Hi I am trying to add a second x axis to my plot using the following data:

 depth     s.den    c.den      bd      car  X  min
1      1 0.3023393 2.859395 0.05735 35.74244  0 2017
2      2 0.3055764 3.373670 0.07015 42.17087  1 1987
3      3 0.3367664 4.629492 0.09165 42.08629  2 1954
4      4 0.3318848 3.789447 0.07765 37.89447  3 1941
5      5 0.3178764 3.432860 0.07075 31.20782  4 1920
6      6 0.2401508 2.808528 0.06045 28.08528  5 1909
7      7 0.3044616 2.480078 0.05715 22.54617  6 1889
8      8 0.4002132 3.250899 0.06770 32.50899  7 1878
9      9 0.4551193 2.901270 0.05735 29.01270  8 1860

I am looking to plot depth and min on opposing x axis, and car on the y axis. this is the code I an currently using. I would like to have depth on the bottom x axis and min on the top. Any help is appreciated.

CAR <- ggplot() 
  geom_line(data = LHB, mapping = aes(x = depth, y = car), col = 'black')  
  ggtitle("CARLHB")  
  xlab("Depth (cm)")  
  ylab(bquote(Carbon~Accumulation~(g~C/m^2/yr^-1))) 
CAR

CodePudding user response:

library(tidypaleo)

model <- age_depth_model(
  depth = cars$min,
  age = cars$depth
)



ggplot(cars, aes(x = depth, y = car))  
  geom_line()  
  scale_x_age_depth(model, depth_name = "min")  
  ggtitle("CARLHB")  
  xlab("Depth (cm)")  
  geom_point()  
  ylab(bquote(Carbon~Accumulation~(g~C/m^2/yr^-1)))

enter image description here hope that works !

CodePudding user response:

EDIT #2: I think the OP just wants a secondary axis that has labels from the min column. Since this is a single, sorted series, we can use the same breaks as the primary axis but with different labels. Much simpler than what I suggested earlier.

ggplot() 
  geom_line(data = LHB, aes(x = depth, y = car), col = 'black')  
  labs(title = "CARLHB", x = "Depth (cm)",
       y = bquote(Carbon~Accumulation~(g~C/m^2/yr^-1)))  
  scale_x_continuous(breaks = 1:9, minor_breaks = NULL,
                     sec.axis = sec_axis(identity, breaks = 1:9, labels = LHB$min)) 

enter image description here


ggplot2 is an opinionated framework, and one of the more controversial opinions is that it discourages secondary axes. See here for some arguments against secondary axes, which Hadley Wickham (creator of ggplot2) has also espoused: enter image description here


Edit: it's also possible you just want to note the years along the top. We could skip axis labels and just plot the text:

ggplot() 
  geom_line(data = LHB, aes(x = depth, y = car), col = 'black')  
  geom_text(data = LHB, aes(x = depth, y = Inf, label = min), vjust = -0.3)  
  # geom_line(data = LHB, aes(x = (min-1850)/20, y = car), col = 'gray60')  
  labs(title = "CARLHB\n", x = "Depth (cm)",
       y = bquote(Carbon~Accumulation~(g~C/m^2/yr^-1)))  
  scale_x_continuous(breaks = 1:9, minor_breaks = NULL)  
  coord_cartesian(clip = "off")

enter image description here

  • Related