Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change legend symbol from geom_boxplot symbol to a square

Can I change the symbol used in the legend for a boxplot? I would like to use a square instead of the boxplot symbol that is the default. I've tried the following after some searching, however the last line does not seem to have an effect:

df = data.frame(x = rnorm(10), y = sample(letters[1:2], 10, TRUE))
library(ggplot2)
ggplot(df, aes(y, x)) +
geom_boxplot(aes(color = y)) +
guides(fill = guide_legend(override.aes = list(shape = 22)))

The reason is that there is another graph left of this one that uses the same colors but points instead of a boxplot, so I would like a legend that works for both.

like image 229
ShellfishGene Avatar asked Oct 21 '25 04:10

ShellfishGene


1 Answers

I guess there are multiple ways to achieve what you want, but what I usually do is:

  1. Remove boxplot legend
  2. Add geom_point layer with size 0
  3. Change legend for geom_point and NOT for geom_boxplot

Code:

df <- data.frame(x = rnorm(10), 
                 y = sample(letters[1:2], 10, TRUE))

library(ggplot2)
ggplot(df, aes(y, x, color = y)) +
    # Add dummy point layer with invisible points (size 0)
    geom_point(size = 0, shape = 22) +
    # Don't show legend
    geom_boxplot(show.legend = FALSE) +
    # Increase point size
    guides(color = guide_legend(override.aes = list(size = 10)))

Result:

enter image description here

like image 58
pogibas Avatar answered Oct 23 '25 22:10

pogibas