Home > Back-end >  How to modify ggplot legend labels
How to modify ggplot legend labels

Time:08-30

I need to provide more descriptive labels, which should be possible without sticking them in the data frame.

dfa <- data.frame(x=rep(1:5,2),y=c(1:5/3,5:1/2),
    gr=factor(rep(1:2,each=5)))
ggplot(dfa,aes(x,y,group=gr,color=gr)) 
    geom_line(aes(linetype=gr),size=1.2) 
    scale_color_hue(labels=c("Big Name 1","Big Name 2"))
# gives me two legends
ggplot(dfa,aes(x,y,group=gr,color=gr)) 
    geom_line(aes(linetype=gr),size=1.2) 
    guides(gr=guide_legend(title="Title",labels=c("Big Name 1","Big Name 2")))
# does not take the labels

CodePudding user response:

You'll need to specify the same label information for each scale_ function associated with the color and linetype aesthetics:

dfa <- data.frame(x=rep(1:5,2),y=c(1:5/3,5:1/2),
                  gr=factor(rep(1:2,each=5)))

ggplot(dfa,aes(x,y,group=gr,color=gr)) 
  geom_line(aes(linetype=gr),size=1.2) 
  scale_color_hue(labels=c("Big Name 1","Big Name 2"))  
  scale_linetype_discrete(labels=c("Big Name 1","Big Name 2"))

enter image description here

Here's an alternate method that modifies the data set just before plotting, but doesn't save any changes to the data. I find this helps cut down on some redundancy in the label specification:

dfa %>% 
  mutate(
    Category = case_when(
      gr == 1 ~ 'Big Name 1',
      gr == 2 ~ 'Big Name 2'
    )
  ) %>% 
  ggplot(.,aes(x,y,group=Category,color=Category)) 
  geom_line(aes(linetype=Category),size=1.2)

enter image description here

  • Related