Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot legend for colour with auxiliary variable

Tags:

r

ggplot2

I'd like to create a plot with a quadratic curve in black, and horizontal lines at various levels in different colours, with a legend (guide) that labels the horizontal line colours. I can't quite figure it out -- I've tried a couple of variations that seem to make sense to me, but I can't seem to force the legend to appear.

Here's my latest attempt:

library(ggplot2)
theme_set(theme_bw()) ## cosmetic
hdat <- data.frame(harvest_rate=c(5,15,25,30))
r <- 1; K <- 100
ggplot(hdat)+
    geom_hline(data=hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
    stat_function(fun=function(x) r*x*(1-x/K),colour="black")+
    expand_limits(x=c(0,110))

enter image description here

The lines come out OK, but the legend/guide is not there.

If I do this instead:

ggplot(hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
    geom_hline()+
    stat_function(fun=function(x) r*x*(1-x/K),colour="black")+
    expand_limits(x=c(0,110))

then to my surprise the horizontal lines don't get drawn at all!

I've also tried (I started this way) setting up a data frame with x and y variables,

 d <- data.frame(x=0:110)
 d <- transform(d,y=r*x*(1-x/K))
 ggplot(d,aes(x,y))+geom_line()+
      geom_hline(data=hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
      scale_colour_brewer(palette="Set1")

The guide doesn't show up that way either.

If I set colour=NA in the initial ggplot call the legend appears, but the curve disappears. If I set colour=factor(1) as follows

 ggplot(d,aes(x,y,colour=factor(1)))+geom_line()+
      geom_hline(data=hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
      scale_colour_brewer(palette="Set1")

I get a curve and a legend, but the curve is in a bogus colour. If I override by setting geom_line(colour="black") then the legend disappears again ...

I would be very grateful for (1) a hack that works and (2) an explanation of the logic that I'm missing!

like image 857
Ben Bolker Avatar asked Feb 23 '26 09:02

Ben Bolker


1 Answers

The complete answer:

library(ggplot2)
theme_set(theme_bw()) ## cosmetic
hdat <- data.frame(harvest_rate=c(5,15,25,30))
r <- 1; K <- 100

ggplot(hdat)+
  geom_hline(aes(yintercept=harvest_rate, colour=factor(harvest_rate)), show_guide=TRUE)+
  stat_function(fun=function(x) r*x*(1-x/K),colour="black")+
  expand_limits(x=c(0,110)) +
  labs(colour = "Harvest rate") # making a pretty legend title

The result:

enter image description here

like image 127
Jaap Avatar answered Feb 25 '26 01:02

Jaap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!