Home > Net >  ggplot2 change line thickness by factor level in density plot
ggplot2 change line thickness by factor level in density plot

Time:10-22

Please help me increase the line thickness of only the density plot where age_cat_maths == '50 to 65'.

This is my current plot: 1

Using aes(scale = age_cat_maths) doesn't work. Any other code improvements are much appreciated.

sq <- sq %>% 
  mutate(age_cat_maths = factor(
                  ifelse(teacher_age_maths >= 18 & teacher_age_maths < 30, '18 to 29',
                  ifelse(teacher_age_maths >= 30 & teacher_age_maths < 40, '30 to 39',
                  ifelse(teacher_age_maths >= 40 & teacher_age_maths < 50, '40 to 49',
                  ifelse(teacher_age_maths >= 50 & teacher_age_maths < 66, '50 to 65', 
                         0 ))))))
sq %>% 
  drop_na(age_cat_maths) %>% 
  select(age_cat_maths, score_teacher_maths) %>% 
  ggplot(aes(x = score_teacher_maths,
             linetype = age_cat_maths,
             scale = age_cat_maths,
             )) 
  geom_density(adjust = 2, na.rm = TRUE,)

CodePudding user response:

You want to map to the size aesthetic, not scale. You'll also have to use scale_size_manual to specify the same size for all values except '50 to 65'.

set.seed(13)
library(ggplot2)

# example data
sq <- data.frame(
  age_cat_maths = factor(sample(
    c('18 to 29', '30 to 39', '40 to 49', '50 to 65'), 
    100, 
    replace = TRUE
  )),
  score_teacher_maths = rnorm(100, 800, 100)
)
                                
sq %>% 
  ggplot(aes(x = score_teacher_maths,
             linetype = age_cat_maths,
             size = age_cat_maths,
  )) 
  geom_density(adjust = 2, na.rm = TRUE)  
  scale_size_manual(values = c(0.5, 0.5, 0.5, 2.5))

  • Related