Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can colour be added manually in ggplot and legend labels renamed in the same plot?

Tags:

r

ggplot2

p <- ggplot(mpg, aes(x= displ, y= hwy, fill = drv)) + 
  geom_bar(stat = "identity") + 
  scale_fill_manual(values = c("forestgreen", "blue", "deepred"))

When I add following code to change legend labels:

p + scale_fill_discrete(labels = c("4wd", "front", " rear"))

I get this error warning:

Scale for 'fill' is already present. Adding another scale for 'fill', which will replace the existing scale.

So it replaces the existing scale and returns to first scale. How can it be prevented?

like image 355
M.R.Wani Avatar asked Oct 25 '25 04:10

M.R.Wani


1 Answers

You need to provide values and labels at the same time.

library(ggplot2)
ggplot(mpg, aes(x= displ, y= hwy, fill = drv)) + 
  geom_bar(stat = "identity") + 
  scale_fill_manual(
    values = c("forestgreen", "blue", "darkred"),
    labels = c("4wd", "front", " rear")
  )

If for some reason you have a plot with scale and want to update the scale, that's fine also, but again you need to set all the parameters you require at once.

library(ggplot2)
p <- ggplot(mpg, aes(x= displ, y= hwy, fill = drv)) + 
  geom_bar(stat = "identity") + 
  scale_fill_manual(
    values = c("forestgreen", "blue", "darkred")
  )

p + scale_fill_manual(
  values = c("forestgreen", "blue", "darkred"),
  labels = c("4wd", "front", " rear")
)
#> Scale for 'fill' is already present. Adding another scale for 'fill',
#> which will replace the existing scale.

like image 132
Claus Wilke Avatar answered Oct 26 '25 17:10

Claus Wilke



Donate For Us

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