Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to rename a legend item in ggplot?

Tags:

r

ggplot2

Can you manually change the items withing a ggplot legend? I currently have a plot which is grouped base on my well numbers. These are classed as numeric. For one of these sites I want to label it as a character i.e. Fernhill. Can I manually rename items within the legend or do I have to create a new field in my dataframe?

like image 369
Simon Avatar asked Oct 16 '25 04:10

Simon


1 Answers

Use the labels parameter in scale_fill_manual or scale_color_manual (or one of the other variants) to specify the name of each legend item respectively.

Reproducible Example 1:

data(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
mtcars$am <- as.factor(mtcars$am)

library(ggplot2)
ggplot(mtcars, aes(x=cyl, y=mpg, fill=am))+
  geom_boxplot() +
  scale_fill_manual(name="Gear Type",labels=c("Automatic", "Manual"), values=c("dodgerblue4", "firebrick4"))

Produces:

enter image description here

Notice that I'm using the labels argument in scale_fill_manual() because I'm filling the aesthetics through fill.

In the following example, because I'm using the color aesthetic mapping (instead of fill), I will use scale_color_manual instead:

Reproducible Example 2:

library(ggplot2)
ggplot(mtcars, aes(x=cyl, y=mpg, color=am))+
  geom_jitter() +
  scale_color_manual(name="Gear Type",labels=c("Automatic", "Manual"), values=c("dodgerblue4", "firebrick4"))

enter image description here

like image 113
onlyphantom Avatar answered Oct 18 '25 22:10

onlyphantom