19

How can I create a legend informing that the red cross is the mean?

ggplot(results, aes(x=factor, y=proportionPositive)) +
geom_boxplot() +
stat_summary(fun.data = "mean_cl_normal", colour = "red", shape=4)

enter image description here

Pengin
  • 4,692
  • 6
  • 36
  • 62

3 Answers3

28

Here is one way of doing it:

  1. Map an aesthetic to a shape, i.e. aes(shape="mean")
  2. Create a manual shape scale, i.e. scale_shape_manual()
# Create dummy data
results <- data.frame(
  factor=factor(rep(1:10, 100)), 
  proportionPositive=rnorm(1000))

# Plot results
ggplot(results, aes(x=factor, y=proportionPositive)) +
      geom_boxplot() +
      stat_summary(fun.data = "mean_cl_normal", 
              aes(shape="mean"), 
              colour = "red",
              geom="point") +
      scale_shape_manual("", values=c("mean"="x"))

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • 2
    If you want to use pch symbolsl it's possible to use Unicode numbers. In order to do that, just replace the 'x' by an Unicode value: "\U" then Unicode value (e.g. `"\U22C4"`). See [Unicode table][1] [1]: http://www.fileformat.info/info/unicode/char/22c4/index.htm – Fábio Dec 06 '16 at 16:26
1

for me option "show.legend=TRUE" simply did work out:

ggplot(aes(x=stimulus, y=EPN, fill=strategy))+ 
  stat_summary(fun.data=mean_se, show.legend=TRUE, geom="bar", position="dodge", colour="black", linetype="solid", size=0.3)
tjebo
  • 21,977
  • 7
  • 58
  • 94
asenga
  • 21
  • 2
  • This surprisingly works, but not without adding a scale call, e.g., as above `... + scale_shape_manual(values=c("mean"="x"))` – tjebo Nov 10 '21 at 17:32
0

To make it appear like a default legend (borrowing from @Andrie code):

ggplot(results, aes(x=factor, y=proportionPositive)) +
      geom_boxplot() +
      stat_summary(fun.data = "mean_cl_normal", 
              aes(shape=""), # Leave empty
              colour = "red",
              geom="point") +
      scale_shape_manual("mean", values= "") # Will show mean on top of the line
Tunn
  • 1,506
  • 16
  • 25