Home > OS >  Changing legend in geom_density
Changing legend in geom_density

Time:12-19

I cannot understand why the legend is not changing given the following code. The same options do the trick with geom_histogram. Thanks in advance for any assistance.

data(mtcars)
ggplot(mtcars, aes(x = disp, color = as.factor(am)))  
  geom_density(aes(group = am))  
  theme_classic()  
  guides(fill = guide_legend(reverse=TRUE))  
  labs(x = "Displacement", y = "Density")  
  scale_fill_manual(name="",values=c("black","gray"),labels=c("Foreign","Domestic"))

CodePudding user response:

You used color in your call of aes(). To modify the scale for this variable you need to use scale_color_manual and not scale_fill_manual.

It's tricky because geom_histogram does use fill, but geom_density uses color.

Working solution :

data(mtcars)
ggplot(mtcars, aes(x = disp, color = as.factor(am)))  
  geom_density(aes(group = am))  
  theme_classic()  
  guides(fill = guide_legend(reverse=TRUE))  
  labs(x = "Displacement", y = "Density")  
  scale_color_manual(name="",values=c("black","gray"),labels=c("Foreign","Domestic"))
  • Related