1

I have been trying to do the next task but without success.

t<-seq(1,5)
y1<-c(0.3,0.25,0.35,0.2,0.4)




 data<-data.frame(t,y1)
 ggplot(data,aes(x=t,y=y1)) + 
      geom_line(color="red") + geom_line(aes(x=t,y=y1+0.2),color="blue")+
   scale_x_discrete(breaks=c("1","2","3","4","5"),labels=c("t-3","t-2","t-1","t","t+1"))+ 
    ylim(0,0.8)

enter image description here What I want is to replace the numbers in the x-axis by t-3,t-2,t-1,t,t+1. I found in other posts that I should use scale_x_discrete, but it doesnt work...

stefan
  • 90,330
  • 6
  • 25
  • 51
user3483060
  • 337
  • 2
  • 13
  • 5
    Are you looking for `scale_x_continuous(breaks=c(1,2,3,4,5),labels=c("t-3","t-2","t-1","t","t+1"))` instead of the discrete scale? – teunbrand Nov 19 '22 at 14:54
  • 1
    yes, that is what I wanted, But not sure about how it works, because I was looking a discrete scale, I mean x values are discrete values. Why continuous?? – user3483060 Nov 19 '22 at 14:58
  • 1
    Your `t` vector is numeric, which ggplot interprets as continuous data. If `t` were character or factor, ggplot would use a discrete scale by default. – jdobres Nov 19 '22 at 15:01

1 Answers1

0

We can do:

data<-data.frame(t,y1)
ggplot(data,aes(x=t,y=y1)) + 
  geom_line(color="red") + geom_line(aes(x=t,y=y1+0.2),color="blue")+ 
  ylim(0,0.8)+
  scale_x_continuous(breaks=c(1,2,3,4,5),labels=c("t-3","t-2","t-1","t","t+1"))

Output: enter image description here

johnjohn
  • 716
  • 2
  • 9
  • 17