0

I have time series data set

y<-c(1,5,12,21,30,50,90,100)

Date = c("2020/07/16","2020/07/23","2020/07/30","2020/08/06","2020/08/13","2020/08/20","2020/08/27","2020/09/13")

if I have an other time series

 q<-c(1,13,18,18,20,30,40,50)

how can I plot it in the same plot?

how to plot this data set show the date on the x-axis ? Thanks

hard worker
  • 181
  • 8

1 Answers1

2

Convert Date to Date class and then add these 2 vectors in a dataframe to use in ggplot.

library(ggplot2)
df <- data.frame(y, Date = as.Date(Date))
ggplot(df) + aes(Date, y) + geom_line()

For multiple values you could get the data in long format and then plot.

df <- data.frame(y, Date = as.Date(Date), q)
df %>%
  tidyr::pivot_longer(cols = -Date) %>%
  ggplot() + aes(Date, value, color = name) + geom_line()

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you for your answer, but I am looking for a time series plot. your code looks produce a graph x label is not the date, and y label looks strange – hard worker Dec 14 '20 at 04:06
  • x label is a date because your data is spread from 2013 to 2020 it is showing only years. Maybe the second date with 2013 is a typo because rest of the dates are in 2020? I don't know why `y` labels look strange to you because that is what you have in your data. Can you double check the data that you have posted? You can edit x-axis to take any format you want by using `scale_x_date`. For example add `+ scale_x_date(date_labels = '%d-%m-%Y')` to above answer. – Ronak Shah Dec 14 '20 at 04:16
  • sorry so it is a typo before. I fixed it now. – hard worker Dec 14 '20 at 04:22
  • @hardworker You can now rerun the above code. What do you find "strange" now in the plot? – Ronak Shah Dec 14 '20 at 04:24
  • it is very good for the plot,sorry my confusion before. I have an extra question if I want to plot another ts q<-c(1,13,18,18,20,30,40,50) in the same plot and the same time period with different color how can I do that? Thank you – hard worker Dec 14 '20 at 04:27
  • You can get the data in long format and plot them. This post covers it exactly https://stackoverflow.com/questions/4877357/how-to-plot-all-the-columns-of-a-data-frame-in-r – Ronak Shah Dec 14 '20 at 04:30
  • still do not know how to do that – hard worker Dec 14 '20 at 04:41
  • You should not ask additional question in comments after your original question has been answered. I have added the answer for your additional question this time but please ask it as a new question next time if you have any such additional questions. – Ronak Shah Dec 14 '20 at 04:48