Hopefully this is a pretty simple question. I am trying to manually label the x-axis for a line graph (temperature) and bar graph (river discharge) with a shared x-axis and different y-axes, yet I have been consistently unsuccessful, and I really don't know why.
My first dataset (bar graph) looks like this:
And my second dataset (line graph) looks like this:
This is the script I wrote that gives me the following image:
p.dt <- ggplot(discharge, aes(x=date,y=discharge)) +
geom_bar(stat="identity",width=1) +
annotate("rect", xmin=1, xmax=152,ymin=0,ymax=850,alpha=.25) +
geom_line(data = temp.ave, inherit.aes = FALSE, aes(x=num, y=average/0.03, group=1), size=2) +
scale_y_continuous(sec.axis = sec_axis(~.*0.03, name = "Temperature (C)")) +
theme_linedraw(base_size = 18) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
strip.text = element_text(face = "bold")) +
theme(axis.text.x = element_blank(), axis.ticks = element_blank()) +
labs(y = "Discharge (cfs)", x = "")
#ggtitle("USGS Gauge 09112200 Discharge and HOBO Temp")
print(p.dt)
Okay. So, I would like to manually label the x-axis every fourth month (example: 11/1/17 to "Nov 2017"), and the data points are shared between the two datasets. I have been adding a single line of scale_x_discrete
after adding the temperature layer as a second axis with no avail:
p.dt <- ggplot(discharge, aes(x=date,y=discharge)) +
geom_bar(stat="identity",width=1) +
annotate("rect", xmin=1, xmax=152,ymin=0,ymax=850,alpha=.25) +
geom_line(data = temp.ave, inherit.aes = FALSE, aes(x=num, y=average/0.03, group=1), size=2) +
scale_y_continuous(sec.axis = sec_axis(~.*0.03, name = "Temperature (C)")) +
scale_x_discrete(labels = c("11/1/17" = "Nov 2017", "3/1/18" = "Mar 2018", "7/1/18" = "Jul 2018")) +
theme_linedraw(base_size = 18) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
strip.text = element_text(face = "bold")) +
theme(axis.text.x = element_blank(), axis.ticks = element_blank()) +
labs(y = "Discharge (cfs)", x = "")
#ggtitle("USGS Gauge 09112200 Discharge and HOBO Temp")
print(p.dt)
I imagine this has something to do with my two y-axes and two separate datasets. Thoughts?
Thank you in advance,
J
You could perhaps have the column date as Posixct and use:
scale_x_datetime(labels = date_format("%m-%Y"), breaks = '4 months') +