macs2021
macs2021

Reputation: 85

Change the x axis from days of the year to months

I have a graphic which shows the trends from different years along the days of the years: enter image description here

The problem is that the x axis is represented by the vector days<-seq(1:366) but I need on the x axis the months for comparation. The data frame is too big but the structure is:

 x    y      group
 1 215.4335  2012
 2 214.1977  2012
 3 212.9618  2012
 4 211.7260  2012
 5 210.4901  2012
 6 209.2543  2012

And my code is:

ggplot(data_ggp, aes(x, y, col = group)) +            
  geom_line()+
  labs(x = " ", y = " ") +
  scale_color_discrete(name = "Trends")+
  theme_bw() +
  theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black"),
        axis.text.x = element_text(size = 8.5))

How can I represent my x axis by the months and not the days of the year? Thank you for your help!

Upvotes: 0

Views: 1160

Answers (1)

r2evans
r2evans

Reputation: 160407

To get month names, you need Dates somewhere. Two options: change your data to be proper dates, or fake it in the breaks= and labels= argument functions. I'll demo the latter.

set.seed(42)
fakedat <- data.frame(x=1:365, y=cumsum(runif(365,0,10)))
head(fakedat)
#   x        y
# 1 1  9.14806
# 2 2 18.51881
# 3 3 21.38021
# 4 4 29.68469
# 5 5 36.10214
# 6 6 41.29310

library(ggplot2)
ggplot(fakedat, aes(x, y)) +
  geom_line()

ggplot, x-axis as integers

breakfunc <- function(x) {
  origin <- as.Date("2021-01-01")
  days <- origin + x
  origin <- as.POSIXlt(origin)
  dayseq <- as.POSIXlt(seq(days[1], days[2], by = "day"))
  with(dayseq, yday[mday == 1] + 365*(year[mday == 1] - origin$year ))
}

labelfunc <- function(x) {
  origin <- as.Date("2021-01-01")
  format(origin + x, format = "%b")
}

ggplot(fakedat, aes(x, y)) +
  geom_line() +
  scale_x_continuous(breaks=breakfunc, labels=labelfunc)

ggplot with month names

Upvotes: 2

Related Questions