Home > Software engineering >  Timeseries plot in R with 2 variables
Timeseries plot in R with 2 variables

Time:12-02

I Have this dataset where i would like to plot a time series of score1 and score2 in R. May I know how could i achieve that?

DT                 Score1  Score2
12-01-21 1:30        1       4
12-02-22 1:30        5       4
12-12-21 1:30        1       4
01-01-22 12:30       0       3
03-02-22 1:00        3       1
03-02-22 1:14        4       1

CodePudding user response:

Using plot() and points()

plot(df$Score1 ~ df$DT)
points(df$Score1 ~ df$DT)

A little more tweaking to make it a bit nicer... there's so much more you can do

plot(df$Score1 ~ df$DT, typ="l", col="black", 
     xlab="Date", ylab="Score")
points(df$Score1 ~ df$DT, typ="l", col="red")

Or for a ggplot (library(ggplot2)) version (again, much tweaking is possible)

data1 %>%
  ggplot(mapping=aes(x=DT, y=Score1))  
    geom_line()  
    geom_line(y=data1$Score2, col="red")

CodePudding user response:

I separated the date from the time and created a plot based on time variable using geom_line() and geom_step()

library(ggplot2)
library(reshape)

data <-data.frame("DT"=c("12-01-21", "12-02-22", "12-12-21", "01-01-22", "03-02-22", "03-02-22"), 
                   "time"=c("1:30","1:30","1:30","12:30","1:00","1:14"),
                   "Score 1"=c(1,5,1,0,3,4),
                   "Score 2" =c (4,4,4,3,1,1))


df<-melt(data)

(plot<-ggplot(df, aes(x=time, y=value, group=variable))    
    geom_line(aes(color=variable), size=1) theme_bw()) # the case of geom_step() is  geom_step(aes(color=variable), size=1)

geom_line() enter image description here

geom_steps()

enter image description here

And facet_wrap based on DT variable

(plot<-ggplot(df, aes(x=time, y=value, group=variable))    
    geom_line(aes(color=variable), size=1) theme_bw() 
  facet_wrap(~DT))

enter image description here

  •  Tags:  
  • r
  • Related