Home > Blockchain >  Is there a way to change the width of the line of a ggplot for a certain x-value?
Is there a way to change the width of the line of a ggplot for a certain x-value?

Time:11-29

This is the code I am using to create a ggplot for the COVID mortality. Each year has a different colour but we also have to make the line thicker in the years 2020 and 2021 but I don't know how to change this specific part of the line. I tried looking it up but all I could find was how to change the width of a full line, not a specific part of it. Anybody any suggestions?

enter image description here

ggplot(data = preds, 
       aes(x=DATE, y=1E7*PER_CAPITA_MORTALITY))  
  geom_line(aes(colour=factor(YEAR), size = 0.01))   
  geom_line(aes(y=1E7*PER_CAPITA_MORTALITY), colour="black", size=0.3)  
  geom_ribbon(aes(ymin=baseline.lower.CI, ymax=baseline.upper.CI), fill="steelblue", 
              colour=NA, alpha=I(0.4))   # 95% confidence intervals (dark grey)
  geom_ribbon(aes(ymin=baseline.lower.PI, ymax=baseline.upper.PI), fill="steelblue", 
              colour=NA, alpha=I(0.2))  
  ggtitle("PREDICTED MORTALITY IN BELGIUM PER 10M PER WEEK)",
          subtitle="dark and light shaded areas = 95% confidence and prediction intervals")  
  xlab("YEAR")   ylab("Predicted mortality (per 10M per week)")  
  theme_grey(base_size = 20)  
  facet_wrap(~ model)

CodePudding user response:

You could use an if_else on the year combined with linewidth (I've used some made-up data in data_df to demonstrate):

library(tidyverse)
library(lubridate)

data_df <- tribble(~date, ~value,
        "2019-01-01", 1,
        "2019-04-01", 2,
        "2019-07-01", 3,
        "2019-10-01", 1,
        "2020-01-01", 1,
        "2020-04-01", 4,
        "2020-07-01", 5,
        "2020-10-01", 2,
        "2021-01-01", 2,
        "2021-04-01", 4,
        "2021-07-01", 5,
        "2021-10-01", 2,
        "2022-01-01", 1,
        "2022-04-01", 2,
        "2022-07-01", 3,
        "2022-10-01", 1) |> 
  mutate(date = ymd(date),
         year = year(date))

data_df |> 
  ggplot(aes(date, value))  
  geom_line(linewidth = if_else(data_df$year %in% c("2020", "2021"), 3, 0.5))

Created on 2022-11-28 with reprex v2.0.2

  • Related