1

I have the following data set

set.seed(10)
start_date <- as.Date('2000-01-01')  
end_date <- as.Date('2000-01-10')   

Data <- data.frame(id = rep((1:1000),10), 
  group = rep(c("0","1"), 25),
  IV = sample(1:100),
  DV = sample(c("1", "0"), 10, replace = TRUE),
  date = as.Date(
       sample(as.numeric(start_date):
              as.numeric(end_date), 1000,
              replace = T), origin = '2000-01-01'))

With that, I create the following plot:

Data %>% mutate(group = factor(group), date = as.POSIXct(date)) %>% 
  group_by(group, date) %>% #group
  summarise(prop = sum(DV=="1")/n()) %>% #calculate proportion 
  ggplot()+ theme_classic() + 
  geom_line(aes(x = date, y = prop, color = group)) +
  geom_point(aes(x = date, y = prop, color = group)) +
  geom_smooth(aes(x = date, y = prop, color = group), se = F, method = 'loess') +
  scale_color_manual(values = c('0' = 'black', '1' = 'darkgrey'),
                     labels = c('0' = 'Remaining sample', '1' = 'Group 1'))

Everything works fine but I'm now trying to change the order of the legend entries (so "Group 1" comes first and then "remaining sample") and the title (to "Legend") and can't figure out how.

Ivo
  • 3,890
  • 5
  • 22
  • 53

2 Answers2

2

Simply reorder the levels of your factor group when you create it in your mutate on the first line below to change the order in the legend then add the name argument to scale_colour_manual on the last line to change the legend's title

Data %>% mutate(group = factor(group, levels = c('1', '0')), date = as.POSIXct(date)) %>% 
     group_by(group, date) %>% #group
     summarise(prop = sum(DV=="1")/n()) %>% #calculate proportion 
     ggplot()+ theme_classic() + 
     geom_line(aes(x = date, y = prop, color = group)) +
     geom_point(aes(x = date, y = prop, color = group)) +
     geom_smooth(aes(x = date, y = prop, color = group), se = F, method = 'loess') +
     scale_color_manual(values = c('0' = 'black', '1' = 'darkgrey'),
                   labels = c('0' = 'Remaining sample', '1' = 'Group 1'), name = "Legend")
Relasta
  • 1,066
  • 8
  • 8
2

Other option is to modify legend with guides(colour = guide_legend(reverse = TRUE))

  ggplot()+ theme_classic() + 
 ...
  guides(colour = guide_legend(reverse = TRUE))
Wolfgang Arnold
  • 1,252
  • 8
  • 17