Reputation: 107
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?
Upvotes: 4
Views: 7653
Reputation: 17790
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.
Upvotes: 5