rggplot2legendgeom-bar

ggplot2 legend not appearing


I'm having trouble producing a legend for my ggplot2 figure of categorical point data with a bar indicating the mean overlaid on top.

plot <- ggplot(df, aes(tree, o18)) 
plot + geom_point() +
    geom_crossbar(data=df2,aes(x=tree,ymin=o18, ymax=o18,y=o18,group=tree), width = 0.5)

where df is in the format:

tree o18
A 15
A 22
B 20
B 19.5
C 15
D 30

and df2 contains the means for each tree category:

tree o18
A 19
B 19.75
C 15
D 30

(data simplified)

My output looks like this: enter image description here

I would like to add a legend to the figure indicating that the points are the o18 values and the lines are the means for each category. However, I can't figure out how to do this. Is there any way to add such a legend in ggplot?


Solution

  • You need to put something in aes for it to appear in the figure legend.

    library(ggplot2)
    
    ggplot(df1, aes(tree, o18)) +
      geom_point(aes(size = "")) +
      geom_crossbar(data=df2,aes(x=tree,ymin=o18, ymax=o18,y=o18,group=tree, linetype = ""), width = 0.5) +
      labs(size = "o18 value", linetype = "mean")
    

    figure_with_legend