I am trying to plot temperature and precipitation by month using ggplot.
Having spent some time getting two y axis (contrary to good plotting theory - i know!), my x axis is now not present.
Any chance I am missing some thing in my code?
Months is created as such
Month <- c(1,2,3,4,5,6,7,8,9,10,11,12)
The rest of the figure is created using the following
gp1 <-ggplot() +
geom_bar(mapping = aes(x = Month, y = Prec * 40 / 1100), stat = "identity",fill="cornflowerblue") +
geom_point(mapping = aes(x = Month, y = meanTemp),col="orange") +
geom_line(mapping = aes(x = Month, y = meanTemp),col="orange") +
geom_point(mapping = aes(x = Month, y = maxTemp),col="red") +
geom_line(mapping = aes(x = Month, y = maxTemp),col="red") +
geom_point(mapping = aes(x = Month, y = minTemp),col="gold") +
geom_line(mapping = aes(x = Month, y = minTemp),col="gold") +
scale_x_discrete(breaks=c(1,2,3,4,5,6,7,8,9,10,11,12), labels=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")) +
scale_y_continuous(name = expression("Temperature ("~degree~"C)"), limits = c(0, 40))
gp1<- gp1 %+% scale_y_continuous(name = expression("Temperature ("~degree~"C)"), sec.axis = sec_axis(~ . * 1100 / 40 , name = "Precipitation (mm)"), limits = c(0, 40))
gp1<-gp1+theme_classic()
gp1
The figure produced looks as such
The problem is that your x-axis is continuous, not discrete.
This is because you have specified numerical values for your x aesthetic. If you were to specify text or factor values for your x aesthetic then your x-axis would be discrete.
Swapping scale_x_discrete
to scale_x_continuous
resolved the issue in my experiments.