user2843490
user2843490

Reputation: 1

Cannot make legend for several density plots in ggplot2

I am using ggplot2 to have some density plots with legends, but I cannot add legend to my final result.

m <- ggplot(chickwts, aes(x = weight))
m + geom_density(kernel = "gaussian", adjust = .3, colour="green", size=1)+
  geom_density(kernel = "gaussian", adjust = 1, colour="red", size=1)+
  geom_density(kernel = "gaussian",adjust = 5, colour="blue", size=1)+
  geom_density(kernel = "gaussian",adjust = 10, colour="yellow", size=1)+
  geom_density(kernel = "gaussian",adjust = 20, colour="orange", size=1)

I have used several syntaxes which I have found here but none of them did not work. Thank you.

Upvotes: 0

Views: 3039

Answers (1)

Andrew
Andrew

Reputation: 38619

ggplot2 bases its legends on aesthetics, or arguments passed to the aes() function. Ordinarily, you'd assign a factor as the color aesthetic, which would create the color legend automatically. However, there is no built-in density grouping factor in the chickwts dataset, so you have to make up your own scale and labels.

Instead of defining the color directly in geom_density(), you can define a named color aesthetic that corresponds to a custom color scale you create in scale_colour_manual(), like so:

m <- ggplot(chickwts, aes(x = weight))
m + geom_density(kernel = "gaussian", adjust = .3, aes(colour=".3"), size=1)+
  geom_density(kernel = "gaussian", adjust = 1, aes(colour="1"), size=1)+
  geom_density(kernel = "gaussian",adjust = 5, aes(colour="5"), size=1)+
  geom_density(kernel = "gaussian",adjust = 10, aes(colour="10"), size=1)+
  geom_density(kernel = "gaussian",adjust = 20, aes(colour="20"), size=1) + 
  scale_colour_manual(values=c(".3"="green", "1"="red", "5"="blue", "10"="yellow", "20"="orange"), name="Densities")

Density plot example

Upvotes: 2

Related Questions