How can I change the title of a ggplot2 legend?

后端 未结 4 640
小蘑菇
小蘑菇 2020-12-25 12:38

I was looking here but I can\'t figure it out.

How can I change the word \"type\" to something else?

相关标签:
4条回答
  • 2020-12-25 13:15

    Add either:

    + scale_fill_discrete(name="Title", labels=c("1","2","3"))
    

    or

    + scale_colour_discrete(name="Title", labels=c("1","2","3"))
    

    depending on the geom.

    I recommend you look into the ggplot2 cheatsheet. https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf

    0 讨论(0)
  • 2020-12-25 13:17

    None of the others worked for me for some reason. In case they failed for you as well, adding this worked for me:

    + guides(fill=guide_legend(title='MY NEW TITLE'))
    
    0 讨论(0)
  • 2020-12-25 13:22

    Just a word to the wise ... all of these options above can be overridden if you do something dumb like I just did. Earlier in my project, I had simply turned off a legend I didn't like using the "themes" parameter within ggplot:

    theme(legend.title = element_blank())
    

    If you do this, no matter what beautiful commands you put in to change the title -- and I tried all of those above -- they won't be overridden by your command to turn the legend off! You have been warned! ;{)

    0 讨论(0)
  • 2020-12-25 13:23

    Add

    + labs(colour = "legend title") 
    

    to your ggplot call. Great resource site is also google group for ggplot2.

    edit: this assumes that colour is the aesthetic in the legend, e.g. qplot(x,y,colour=z). If another aesthetic is being shown in the legend, use that as the argument instead, e.g. + labs(fill = "legend title") for a raster/image plot.

    More generally, if you specify an explicit scale such as scale_colour_continuous, you can set the scale_name argument (warning: the details of the arguments to scales may have changed in recent releases of ggplot2; this description is of version 0.9.2.1).

    0 讨论(0)
提交回复
热议问题