Kipras Kančys
Kipras Kančys

Reputation: 1779

How to add legend to geom_ribbon plot?

I have simple plot

set.seed(100)
df <- data.frame(x = 1:100, y = sort(rnorm(100)))

ggplot(data=df, aes(x=x, y=y)) + 
    geom_line() + 
    geom_ribbon(data=df[df$y < 0, ], aes(ymin=y,ymax=0), fill="blue", alpha=0.5) + 
    geom_ribbon(data=df[df$y > 0, ], aes(ymin=0,ymax=y), fill="orange", alpha=0.5)

enter image description here

I would love to add legend explaining blue and orange regions. Tried adding show.legend = TRUE inside geom_ribbon but that doesn't change anything.

Upvotes: 0

Views: 152

Answers (1)

Jon Spring
Jon Spring

Reputation: 66970

ggplot(data=df, aes(x=x, y=y)) + 
  geom_line() + 
  geom_ribbon(data=df[df$y < 0, ], aes(ymin=y,ymax=0, fill="negative"), alpha=0.5) + 
  geom_ribbon(data=df[df$y > 0, ], aes(ymin=0,ymax=y, fill="positive"), alpha=0.5) +
  scale_fill_manual(values = c("positive" = "orange", "negative" = "blue" ), 
                    breaks = c("positive", "negative")) # this controls the order of appearance

enter image description here

Upvotes: 1

Related Questions