Home > database >  How do I chronologically plot weeks with a change of years in R?
How do I chronologically plot weeks with a change of years in R?

Time:11-28

I have the following data frame:

week year politicalization_sum
52 2020 5
53 2020 10
1 2021 0
2 2021 4
3 2021 11

For this data frame, I want to plot the course of politicalization_sum chronologically. I tried the following:

per_week <- per_week %>%
  arrange(desc(week))

ggplot(per_week, mapping = aes(x = week, y = politicalization_sum))  
  geom_point()  
  geom_smooth()

With this, the x-axis starts at week 0 and goes to week 53, with a large gap in the middle. What can I do to have the x-axis start at week 52 in 2020 and end at week 3 in 2021?

CodePudding user response:

Something like this?

library(lubridate)
library(ggplot2)
library(dplyr)
per_week %>% 
  mutate(x = make_date(year)) %>% 
  mutate(date = x   lubridate::weeks(week-1)) %>% 
  ggplot(aes(date, politicalization_sum))  
  scale_x_date(date_labels = "%Y (%b)") 
  geom_point() 
  geom_smooth()

enter image description here

  • Related