Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't show shape in color legend in a 2 legend plot (R ggplot2)

In my plot with 2 legends (one for shape and one for color), my boss finds it confusing that the color legend already has selected one of the shapes. An example:

a <- data.frame(name = c("A","B","C","D"),
                type = c("dog","dog", "cat", "cat"),
                location = c("house", "house", "house", "garden"),
                count = c(3,1,5,8))

ggplot(a, aes(x=name, y=count, color=location, shape=type)) +
  geom_point(size=7)

produces the following: enter image description here

In this example, the 'location' legend is explaining the colors by showing colored circles (but circles also mean cat, which is apparently confusing). How can I force the 'location' legend to JUST show color, not a shape? Maybe showing location as red and blue rectangles would be ideal.

like image 320
Amit Kohli Avatar asked Nov 15 '25 14:11

Amit Kohli


2 Answers

You can use function guides() and override.aes= to change the shape to rectangule for the color legend. Then you can remove background from legend keys for better look with theme().

ggplot(a, aes(x=name, y=count, color=location, shape=type)) +
      geom_point(size=7)+
      guides(color=guide_legend(override.aes=list(shape=15)))+
      theme(legend.key=element_blank())

enter image description here

like image 86
Didzis Elferts Avatar answered Nov 18 '25 05:11

Didzis Elferts


For removing the shape legend, you could do the following:

ggplot(a, aes(x=name, y=count, color=location, shape=type)) +
geom_point(size=7) + 
guides(shape=FALSE)

This removes the shape legend, but I'm not sure about changing the shape in the colour legend.

like image 23
Martijn vd Voort Avatar answered Nov 18 '25 06:11

Martijn vd Voort



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!