Luka
Luka

Reputation: 113

Setting dates on x-axis with ggplot2

I've gone through all similar questions, but still I struggle to find a solution to my problem.

I have this code:

finl <- as.data.frame(cbind(plus,centre,minus,indx))
head(finl)

> head(finl)
     plus    centre     minus indx
1 0.5202951 0.3699147 0.2195342    1
2 0.5328857 0.3890009 0.2451162    2
3 0.5421306 0.3979195 0.2537085    3
4 0.6421294 0.5154826 0.3888357    4
5 0.7312431 0.6132432 0.4952434    5
6 0.7325199 0.6089201 0.4853203    6


ggplot(finl) +
geom_line(aes(indx,centre), group = 1) +
geom_ribbon(aes(x = indx, ymax = plus , ymin = minus), alpha = 0.6, fill = "skyblue") +
ggtitle("Movement over time")+
theme(plot.title = element_text(size=20, face = "bold")) +
theme(plot.title = element_text(hjust = 0.5)) +
theme(axis.text.x=element_blank(),
    axis.ticks.x=element_blank(), 
    axis.title = element_text(size=14))+
labs(x="Period", y="Y-value")

And here is the graph - Plot

Also I have variable date:

date <- ldate[-c(length(ldate))]
date <- as.Date(date)
head(date)

> head(date)
[1] "2008-11-28" "2008-12-31" "2009-01-30" "2009-02-27" "2009-03-31" "2009-04-30"

My question is how to put these dates as an x-axis on my graph?

I've tried with scale_x_date, but somehow I am not able to solve this problem and to get appropriate graph. I get some strange results.

Thank you in advance.

Upvotes: 0

Views: 247

Answers (1)

Erdem Akkas
Erdem Akkas

Reputation: 2060

First insert the dates into the dataframe:

finl<-cbind(finl,date)

Then replace indx with the date column of finl in your ggplot code

Upvotes: 2

Related Questions