ggplot2 legend not appearing

40 views Asked by At

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?

2

There are 2 answers

0
benson23 On BEST ANSWER

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

0
Josep Pueyo On

The @benson23 answer is correct, if you want more control you can use manual scales for different aesthetics. If you use linetype in aes instead of fill, you will get a legend as above, if you like that more.

library(tidyverse)

df <- tribble(
  ~ tree,   ~ o18,
  "A",  15,
  "A",  22,
  "B",  20,
  "B",  19.5,
  "C",  15,
  "D",  30
)

df2 <- tribble(
  ~ tree,   ~ o18,
  "A",  19,
  "B",  19.75,
  "C",  15,
  "D",  30
)

shapes <- c("o18 values" = 16)
fills <- c("Means" = "black")

ggplot(df, aes(tree, o18)) +
  geom_point(aes(shape = "o18 values")) +
  geom_crossbar(data=df2,aes(x=tree,ymin=o18, ymax=o18,y=o18,group=tree, fill = "Means"), width = 0.5) +
  scale_shape_manual(values = shapes, name = "") +
  scale_fill_manual(values = fills, name = "")

Created on 2024-02-09 with reprex v2.0.2