user15791858
user15791858

Reputation: 185

Merging 2 Legends In a Specific way

I have a plot of my data that includes both a boxplot and a point plot (data from mtcars for illustration)

ggplot(mtcars,aes(x=factor(cyl), y=mpg), fill=factor(carb),shape=factor(vs))+
     geom_boxplot(data=subset(mtcars,am==1),aes(x = factor(cyl), y = mpg,fill=factor(carb),shape=factor(vs)),outlier.shape = NA, alpha = 0.85, width = .65, colour = "BLACK") +
      geom_point(data=subset(mtcars,am==1 & vs==1),aes(x = factor(cyl), y = mpg,fill=factor(carb),shape=factor(vs)),outlier.shape = NA,size=5,alpha=.4,shape=1, colour = "BLACK", position = position_dodge(width = 0.65)) 

my objective is for there

  1. to be a single legend instead of two legends
  2. that now shows all the colors associated with the fill (based on carb) and a single element which explains what the open circles correspond to (i.e. vs==1).
  3. for that single element (that corresponds to geom_point) to display an open circle (corresponding to the open circle in the graph) and not boxplots as its currently showing.

any help will be greatly appreciated

Upvotes: 2

Views: 74

Answers (1)

tjebo
tjebo

Reputation: 23807

Remove the shape aesthetic from geom_boxplot. Also, in general no need to specify color = "black", as this is the default for geom_boxplot (same for geom_point).

The version I was running online threw a warning regarding outlier.shape, so I have removed that.

Add shape as constant aesthetic to point and use scale_shape_manual to define your shape (use shape = 21 if you want a fill - your code suggests this, or shape = 1, if you don’t.). When you remove the legend title, the legends look fairly "merged".

However, Not sure what you exactly mean with "merged legend" . Mind showing a desired output?

library(ggplot2)

ggplot(mtcars,aes(x=factor(cyl), y=mpg), fill=factor(carb),shape=factor(vs))+
  geom_boxplot(data=subset(mtcars,am==1), aes(x = factor(cyl), y = mpg, fill=factor(carb)), alpha = 0.85, width = .65) +
  geom_point(data=subset(mtcars,am==1 & vs==1),aes(x = factor(cyl), y = mpg,fill=factor(carb), shape = "v = 1"), size=5, alpha=.4, position = position_dodge(width = 0.65)) +
  scale_shape_manual(NULL, values = 21)

enter image description here

Upvotes: 1

Related Questions