Search code examples
rggplot2legend

Add additional legend to ggplot without extra packages


I have a ggplot with two sets of points for different subjects (x-axis) connected by lines. A legend is generated for them. Then I want to add a transformation of the points for each subject, such as the arithmetic mean, and get a separate legend to explain the additional points (these points are not connected by lines).

Is there a way to do that within ggplot?

library(tidyverse)
y1 <- c(10,20,25)
y2 <- c(20,40,30)

adf <- data.frame(x=c('a','b','c'),y1=y1,y2=y2)

ldf <- adf |> pivot_longer(cols=c(y1,y2), names_to='ymethod',values_to='yval')

p <- ggplot(data=ldf)+
  geom_point(aes(x=x,y=yval, colour = ymethod)) +
  geom_line(aes(x=x,y=yval, colour = ymethod,group=ymethod))


# want an separate legend for these (points not joined by lines)
# called 'Mean' showing a single black point
p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)), 
                aes(x=x,y=am))

# doesn't do what I want
#p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)), 
#                  aes(x=x,y=am),col='black', show.legend = T) 

# doesn't do what I want
#p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)), 
#                  aes(x=x,y=am, col='black'), show.legend = T) 
  
# doesn't do what I want
#p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)), 
#                  aes(x=x,y=am, col='mean'), show.legend = T) +
#  scale_color_manual(values=c('mean'='black'))

print(p)

enter image description here


Solution

  • ggplot(data=ldf)+
      geom_point(aes(x=x,y=yval, colour = ymethod)) +
      geom_line(aes(x=x,y=yval, colour = ymethod,group=ymethod)) +
      geom_point(data=adf|>mutate(am=0.5*(y1+y2)), 
                 aes(x=x,y=am, fill = "mean")) +
      guides(fill=guide_legend(title=element_blank()))
    

    Created on 2024-11-07 with reprex v2.0.2