0

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 Answers 2

1

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

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.