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?
Asked
Active
Viewed 1.2k times
2
-
1Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Apr 05 '19 at 04:07
-
@Simon did the answer I posted help? Let me know if it did (or didn’t) and if additional context / info is needed on top of the solution I provided – onlyphantom Apr 06 '19 at 18:57
-
1@onlyphantom, thanks heaps for the help. I managed to get it working in the end thanks to the examples you gave. – Simon Apr 07 '19 at 21:05
2 Answers
10
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:
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"))

onlyphantom
- 8,606
- 4
- 44
- 58
-
2What if I don't want to assign colors and I want only to change the labels? – Herman Toothrot Oct 07 '20 at 11:00