mehmo
mehmo

Reputation: 485

adding legend for confidence band inside line chart and change the colour

I am trying to add legend for confidence band inside my line chart and change the color of confidence band to light blue.

Here is my code:

co1<- tibble(age= c("10-14","15-19","20-24","25-29","30-34","35-39","40-44" ,"45-49"), pop=c(10:17), lower= c(8.5:15.5),upper=c(12.5:19.5), country =1)
co2<- tibble(age= c("10-14","15-19","20-24","25-29","30-34","35-39","40-44" ,"45-49"), pop=c(11:18), lower= c(9.5:16.5),upper=c(13.5:20.5), country =2)
co3<- tibble(age= c("10-14","15-19","20-24","25-29","30-34","35-39","40-44" ,"45-49"), pop=c(12:19), lower= c(10.5:17.5),upper=c(14.5:21.5), country =3)
df<- rbind(co1,co2,co3)

By the code below, I got line chart with confidence band for three countries:

ggplot(df, aes(x=age, y= pop, group= country)) + 
  geom_line(aes(), size=1) + 
  geom_ribbon(aes(ymin=lower, ymax=upper),alpha=0.2,linetype=2)+
  labs(x = "age", y = "population") +
  facet_wrap(~country)

My expected output would be something like this:

Expected Output

Upvotes: 0

Views: 134

Answers (1)

stefan
stefan

Reputation: 124183

To get a legend you have to map on the fill aesthetic. The color could then be set via scale_fill_manual. The legend itself could be positioned via theme options legend.justification and legend.position:

library(ggplot2)

ggplot(df, aes(x = age, y = pop, group = country)) +
  geom_line(aes(), size = 1) +
  geom_ribbon(aes(ymin = lower, ymax = upper, fill = "conf"), alpha = 0.2, linetype = 2) +
  scale_fill_manual(values = c(conf = "steelblue"), labels = c(conf = "95% prediction interval")) +
  labs(x = "age", y = "population", fill = NULL) +
  facet_wrap(~country) +
  theme(
    legend.justification = c(.025, .95),
    legend.position = c(.025, .95)
  )

Upvotes: 1

Related Questions