在scale_color_manual中更改图例条目顺序和图例标题

时间:2018-03-28 08:25:49

标签: r ggplot2

我有以下数据集

Option Explicit

Private Sub UserForm_Initialize()
    Dim opt As Variant
    Set opt = Me.Controls.Add("Forms.checkbox.1", "CheckBox1", True)
End Sub

Private Sub CommandButton1_Click()
    If Not Me.Controls("CheckBox1") Then
        MsgBox "F"
    End If
End Sub

有了这个,我创建了以下情节:

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'))

一切正常但我现在正在尝试更改图例条目的顺序(因此“组1”首先出现,然后是“剩余样本”)和标题(到“图例”)并且无法弄清楚如何。

2 个答案:

答案 0 :(得分:1)

只需在下面第一行的mutate中创建因子组的级别时重新排序,以更改图例中的顺序,然后将name参数添加到最后一行的scale_colour_manual更改图例的标题

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")

答案 1 :(得分:1)

其他选项是使用guides(colour = guide_legend(reverse = TRUE))

修改图例
  ggplot()+ theme_classic() + 
 ...
  guides(colour = guide_legend(reverse = TRUE))