简体   繁体   中英

How to modify ggplot legend labels

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

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

在此处输入图像描述

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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM