2

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?

Simon
  • 295
  • 1
  • 4
  • 12
  • 1
    Could 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 Answers2

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:

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

onlyphantom
  • 8,606
  • 4
  • 44
  • 58
5

If you don't want to assign colors and only to change the labels:

scale_color_*discrete*(name="Gear Type",labels=c("Automatic", "Manual"))
Gorka
  • 1,971
  • 1
  • 13
  • 28
Tsaksik
  • 51
  • 1
  • 1