Ruediger Ziege
Ruediger Ziege

Reputation: 330

Change the legend coloring in ggplot2 with geom_areas only

I have the following ggplot object:

ggplot(data.frame(x = c(3, 15)), aes(x)) + 
  geom_area(aes(color = "Gruppe A"), stat = "function", fun = dnorm, args = list(mean = 10, sd = 2), fill = "blue", alpha=.5, xlim = c(3, 15)) +
  geom_area(aes(color = "Gruppe B"), stat = "function", fun = dnorm, args = list(mean = 9, sd = 2), fill = "red", alpha=.5, xlim = c(3, 15)) +
  scale_fill_discrete(name = "Name", labels = c("Gruppe A", "Gruppe B")) +
  scale_color_manual(values=c("Gruppe A"="blue", "Gruppe B"="red")) +
  scale_x_continuous(name = "Note", breaks = c(3:15), limits = c(3, 15)) + 
  scale_y_continuous(name = "Dichte")

I tried to add a legend manually by adding scale_color_manual. However, the legend fill color does not match the colors of the geom_area layers. How can I configure this fill color manually?

Upvotes: 2

Views: 554

Answers (1)

kath
kath

Reputation: 7724

You are close, but your code needs some additional tweaking:

Specify also the fill-color inside the aes-call. You can then use scale_fill_manual to specify the colors for filling. As you have the same color for filling and for the outside bound you can specify aesthetics = c("color", "fill") to apply it to both aesthetics.

ggplot(data.frame(x = c(3, 15)), aes(x)) + 
  geom_area(aes(color = "Gruppe A", fill = "Gruppe A"), stat = "function", fun = dnorm, args = list(mean = 10, sd = 2), alpha=.5, xlim = c(3, 15)) +
  geom_area(aes(color = "Gruppe B", fill = "Gruppe B"), stat = "function", fun = dnorm, args = list(mean = 9, sd = 2), alpha=.5, xlim = c(3, 15)) +
  scale_fill_manual(name = "Name", values = c("Gruppe A" = "blue", "Gruppe B" = "red"), aesthetics = c("color", "fill")) +
  scale_x_continuous(name = "Note", breaks = c(3:15), limits = c(3, 15)) + 
  scale_y_continuous(name = "Dichte")

enter image description here

Upvotes: 4

Related Questions