I have a dataset with Year and Month number that I am trying to plot against another variable, in this case "MEI". Here is a small sample of the data:
Year, Month, MEI,
1983, 5, 2.556,
1983, 6, 2.167,
1983, 7, 1.741,
1983, 8, 1.13,
1983, 9, 0.428,
1983, 10, 0.002,
1983, 11, -0.176,
1983, 12, -0.176,
1984, 1, -0.339,
1984, 2, -0.565,
Is there a way to make the x axis continuous over the years (Months-11,12,1,2). I tried:
plot(weather$Month, weather$MEI, main = 'Regression for MEI Each Month Over 16.5 Years',
xlab = 'Month (From May 1983 to December 2008', ylab = 'MEI')
One solution is to generate dates from the year/month values by adding "01" as the day. You can do that using dplyr::mutate
. If you use ggplot2
for plotting, it will make formatting a date x-axis easier too.
library(dplyr)
library(ggplot2)
weather %>%
mutate(Date = as.Date(paste(Year, Month, "01", sep = "-"))) %>%
ggplot(aes(Date, MEI)) +
geom_point() +
scale_x_date(date_labels = "%b %Y")
You could convert the months and the year to a date and then plot the date against MEI
:
weather$date <- as.Date(paste0(weather$Year, "-", weather$Month, "-01"))
plot(weather$date, weather$MEI, main = 'Regression for MEI Each Month Over 16.5 Years',
xlab = 'Month (From May 1983 to December 2008', ylab = 'MEI')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.