The issue I am trying to fix is that one of my temperature loggers stopped early. This causes the x axis to be a different length to the others (See image Axis). I want to extend the axis to be the same for plotting next to each other with an end date/time of 2022-06-06 00:00:00.
Any suggestions on how to adjust this? I've pasted the main 3 chunks of code used to transform data and plot below. Thanks
SD1b <- SaxDeep1b
SD1b$datetime <- as.POSIXct(strptime(SD1b$datetime,format="%d/%m/%Y %H:%M",tz="Australia/Brisbane"))
head(SD1b)
SD1comb$datehour <- cut(as.POSIXct(SD1comb$datetime, format="%Y-%m-%d %H:%M:%S"),breaks="hour")
SD1hourlyT <- aggregate(temp ~ datehour,SD1comb,mean)
head(SD1hourlyT)
SD1hourlyT$datehour <- as.POSIXct(strptime(SD1hourlyT$datehour,format = "%Y-%m-%d %H",
tz="Australia/Brisbane"))
str(SD1hourlyT)
jpeg(file='SD1_temp.jpeg',width=19,height=10,res=1200,units="cm")
SD1temp <- ggplot(SD1hourlyT, aes(x = datehour, y = temp))
geom_line(colour="black")
labs(x=element_blank(),y=expression("Temperature " ( degree*C)) )
scale_x_datetime(date_breaks="1 month",date_labels = "%b") #see ?strptime for labs
scale_y_continuous(limits=c(23,33),breaks=c(23,25,27,29,31,33))
theme_linedraw()
theme_minimal()
theme(axis.text.x = element_text(colour="black",size=10),
axis.title.x = element_text(color = "black", size=12),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
axis.text.y = element_text(colour="black",size=10),
axis.title.y = element_text(color = "black", size=12))
ggtitle("Saxon Deep 1")
CodePudding user response:
You can use the limits
argument within scale_x_datetime
to expand the scale.
library(dplyr)
library(ggplot2)
library(scales)
library(lubridate)
# Example data
df <- data.frame(date = as.POSIXct(
c(
"2016-12-05-16.25.54.875000",
"2016-12-06-15.25.54.875000",
"2016-12-08-14.25.54.875000",
"2016-12-09-13.25.54.875000",
"2016-12-09-12.25.54.875000",
"2016-12-10-11.25.54.875000",
"2016-12-10-10.25.54.875000",
"2016-12-11-07.25.54.875000"
),
format = "%Y-%m-%d-%H.%M.%S"
) ,
y = 1:8)
Default axis limits
The minimum and maximum values of date
are the default limits, even if there is no label or tick mark at the spot.
ggplot(df, aes(x = date, y = y))
geom_point()
scale_x_datetime(labels = date_format("%D"),
date_breaks = "2 day")
Expanded axis limits
We can expand the axis limits even to values not observed in our data. Once again, you'll need to adjust labels and tick marks if you want to scale them the same as well.
ggplot(df, aes(x = date, y = y))
geom_point()
scale_x_datetime(
labels = date_format("%D"),
date_breaks = "2 day",
limits = ymd_h("2016-12-05 00", "2016-12-20 23")
)