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?
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.
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:

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

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With