1

How do I plot each year as a separate line in ggplot2 I tried the below code but it seems to plot continuous as a single plot.

library(ggplot2)

# Dummy data
data <- data.frame(
  Date = c(as.Date("2017-01-14") - 0:13,as.Date("2016-01-14") - 0:13),
  value = runif(28) 
)
#data$Date <- strptime(data$Date, "%Y-%m-%d" )
data$Year <- as.character(year(data$Date))
data$Year <- factor(data$Year)

ggplot(data) + geom_line(aes(x = Date, y = value, group=Year, color=Year)) +
  scale_x_date(date_breaks = "1 day", date_labels = "%d-%m-%y") +
  theme(axis.text.x = element_text(angle = 90))

enter image description here But I want each year to be a separate graph in the same plot.

something like below

enter image description here

1 Answer 1

3

Try this approach formating day and month in your date. You got a mess in your plot because of the different year in your date variable. Setting format can help you. Here the code:

library(ggplot2)
library(lubridate)
# Dummy data
data <- data.frame(
  Date = c(as.Date("2017-01-14") - 0:13,as.Date("2016-01-14") - 0:13),
  value = runif(28) 
)
data$Year <- as.character(year(data$Date))
data$Year <- factor(data$Year)
#Format month
data$MonthDay <- format(data$Date,'%b-%d')
#Plot
ggplot(data) + geom_line(aes(x = MonthDay, y = value, group=Year, color=Year)) +
  theme_bw()+
  theme(axis.text.x = element_text(angle = 90))

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way I can give day breaks of 3 or more days to the x-axis scale. The x-axis seems to be too messy when I plot whole year. Month wise scale perhaps?
@Aprilian8 Hi dear. Yes you can but you would have to create a customized labels.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.