remove legend title in ggplot

前端 未结 5 1772
死守一世寂寞
死守一世寂寞 2020-12-23 02:45

I\'m trying to remove the title of a legend in ggplot2:

df <- data.frame(
  g = rep(letters[1:2], 5),
  x = rnorm(10),
  y = rnorm(10)
)

lib         


        
相关标签:
5条回答
  • 2020-12-23 03:05

    Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name argument of the scale_ function to NULL, i.e.

    scale_fill_discrete(name = NULL)

    (kudos to @pascal for a comment on another thread)

    0 讨论(0)
  • 2020-12-23 03:07

    You were almost there : just add theme(legend.title=element_blank())

    ggplot(df, aes(x, y, colour=g)) +
      geom_line(stat="identity") + 
      theme(legend.position="bottom") +
      theme(legend.title=element_blank())
    

    This page on Cookbook for R gives plenty of details on how to customize legends.

    0 讨论(0)
  • 2020-12-23 03:09

    Another option using labs and setting colour to NULL.

    ggplot(df, aes(x, y, colour = g)) +
      geom_line(stat = "identity") +
      theme(legend.position = "bottom") +
      labs(colour = NULL)
    

    0 讨论(0)
  • 2020-12-23 03:15

    For Error: 'opts' is deprecated. Use theme() instead. (Defunct; last used in version 0.9.1)' I replaced opts(title = "Boxplot - Candidate's Tweet Scores") with labs(title = "Boxplot - Candidate's Tweet Scores"). It worked!

    0 讨论(0)
  • 2020-12-23 03:26

    This works too and also demonstrates how to change the legend title:

    ggplot(df, aes(x, y, colour=g)) +
      geom_line(stat="identity") + 
      theme(legend.position="bottom") +
      scale_color_discrete(name="")
    
    0 讨论(0)
提交回复
热议问题