Home > Software design >  Plotting data in order of date
Plotting data in order of date

Time:02-12

The aim is to plot a historical plot in r. using the following data

      date new_cases
1   22/01/2020        NA
2   23/01/2020         0
3   24/01/2020         1
4   25/01/2020         0
5   26/01/2020         3
6   27/01/2020         0
7   28/01/2020         0
8   29/01/2020         1
9   30/01/2020         0
10  31/01/2020         2

... etc. 

I have never plotted like this, the only thing I know is using

plot(data$new_cases)

But surely there is a more a aesthetically pleasing way to do this? Thanks

CodePudding user response:

In base R, you can convert the date column to date (as suggested above) using as.Date. Then, you can plot and label your graph.

df$date <- as.Date(df$date, "%d/%m/%Y")
plot(new_cases ~ date, df, xaxt = "n", type = "l")
axis(1, df$date, format(df$date, "%d/%m/%Y"), cex.axis = .7)

enter image description here

Another option is to use tidyverse and convert the date, then pipe into ggplot2:

library(tidyverse)

df %>% 
  mutate(date = as.Date(date, format =  "%d/%m/%Y")) %>% 
  ggplot(aes(date,new_cases))  
  geom_line()

enter image description here

Or if you just want points, then you can do as @Dave2e suggested:

df$date <- as.Date(df$date, "%d/%m/%Y")

plot(x=df$date, y=df$new_cases)

enter image description here

  • Related