I am taking over a project where all the figures were created in excel and I am trying to recreate them in ggplot2 now for future reports. I am plotting a dual y-axis plot to visually represent the relationship between when the site had high rainfall and what the water depth at the time was. Below is a made up sample of our data. I want to keep the left and right axis in the same position they are (left is still left and right is still right) but I would like the lines to be overlaid on top of the bars rather than behind as they are now. I can easily fix this by making the right axis the left but for continuity with previous years I don’t want to do that. Thank you or your help. Below is my code with some dummy data:
library(ggplot2)
library(dplyr)
library(lubridate)
Date <- c("2021-01-01","2021-01-01", "2021-01-05", "2021-01-05","2021-01-10", "2021-01-10", "2021-01-15","2021-01-15")
Rainfall <- c(0.75, 0.5, 0.63, 0.9,0.5, 0.63, 0.9,0.6)
Pool <- c("A","B","A","B","A","B","A","B")
WaterDepth <- c(18,22,17,19,15,24,13,11)
Var4 <- c(1000, 987,905,1002)
nine <- data.frame(Date, WaterDepth,Pool,Rainfall, Var4)
nine<-nine %>% mutate(Date = ymd(Date))
nine
scale2=.05
figa <- ggplot() +
geom_line(aes(x=nine$Date,y = nine$WaterDepth, color=nine$Pool),linewidth=1.5)+
geom_col(aes(x=nine$Date, y = nine$Rainfall/scale2,fill="Rainfall"),width=1,alpha=1)+
scale_fill_manual(values = c("#0070C0"))+
scale_color_manual(values=c("#C55A11","#99CC00"))+
labs(
x="Date",y="Water Depth (cm)")+
scale_y_continuous(sec.axis = sec_axis(~.*scale2, name="Rainfall (cm)"),expand=c(0,0),limits=c(0,30)) +
theme(legend.position="bottom",
legend.title=element_blank(),
legend.key.width=unit(.5,"cm"),
legend.key.height=unit(.2,"cm"))+
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.text=element_text(size=10),
axis.title=element_text(size=13))+
labs(color = "Legend")
figa