ggplot2 legend for stat_summary

后端 未结 2 2054
[愿得一人]
[愿得一人] 2020-12-05 03:22

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.         


        
相关标签:
2条回答
  • 2020-12-05 04:03

    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

    0 讨论(0)
  • 2020-12-05 04:08

    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
    
    0 讨论(0)
提交回复
热议问题