r – ggplot2 legend not appearing

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

Read more here: Source link