I am making a plot (in ggplot2) where the x axis ranges from julian day 1-365. Is there any way to add month labels and tick marks to a julian day axis?
(i.e.,scale_x_date)
Thanks!
To set labels for X and Y axes in R plot, call plot() function and along with the data to be plot, pass required string values for the X and Y axes labels to the “xlab” and “ylab” parameters respectively. By default X-axis label is set to “x”, and Y-axis label is set to “y”.
To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.
In R, the julian function converts a date-time object into a Julian date: the number of day since day 0 (default is 1970-01-01). However, there is no function, without loading another package, that converts a Julian date back into a date object. The julian2date function does this conversion.
The first two digits are the last numbers of the year and the three digits after the hyphen are the day of that year. So, for instance, a Julian date of 21-001 represents the first day of the year 2021, or January 1, 2021, while a Julian date of 22-165 represents the 165th day of the year 2022 or June 14, 2022.
You were on the right track with scale_x_date()
, but your Julian days do need to be formatted as Dates first. The trick is selecting an origin that makes sense for your data, and then using scale_x_date()
to format the labels:
library(ggplot2)
# make data
value <- rnorm(365, mean = 0, sd = 5)
jday <- 1:365 # represents your Julian days 1-365; assumes no leap years
# make data frame and add julian day
d <- data.frame(jday = jday, value = value, stringsAsFactors = FALSE)
head(d)
# plot with date labels on x axis
ggplot(d, aes(x = as.Date(jday, origin = as.Date("2018-01-01")), y = value)) +
geom_line() +
scale_x_date(date_labels = "%b")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With