2

Hi im trying to add my legend area to my plot area without the white borders around my key. So far i have this:

Legend in plot area but white border present:

legend1

Legend style i want:

legend2

ggplot(data=Pig, aes(x=breed, y= p1_plus_p3_fat_depth_mm, color=sex))+
geom_boxplot()+
theme(legend.title=element_blank()) +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank())+
xlab("Pig Breed") +
ylab("The P1 and P3 Fat Depth in mm")+
scale_colour_discrete(name  ="Sex",breaks=c("B", "S"),labels=c("Boar", "Sow"))+
theme(legend.justification = c(1, 1), legend.position = c(1, 1))+
theme(legend.background = element_rect(fill="transparent"))
camille
  • 16,432
  • 18
  • 38
  • 60
TPre
  • 25
  • 4
  • I don't see why the `legend.background` setting shouldn't work; the same thing with a different set of data is getting me something similar to your desired output. But without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), we can't see what might be going wrong – camille Feb 25 '19 at 12:43
  • @camille Thankyou for your comment. The legend.background is making the otherwise white background transparent but its as if the borders around the keys are needing something else. Im very new to this, i dont know how to do a reproducible example, sorry. Thankyou for the the feedback – TPre Feb 25 '19 at 13:04
  • The link I posted has lots of suggestions for how to make an example it's easy to help with – camille Feb 25 '19 at 13:25

1 Answers1

1

You will need to use legend.key = element_blank() to drop the background and borders around the boxplot icons.

ggplot(data=iris[c("Species", "Sepal.Length")], aes(x=Species, y= Sepal.Length, color=Species))+
  geom_boxplot()+
  theme(legend.title=element_blank()) +
  theme(panel.grid.major = element_blank()) +
  theme(panel.grid.minor = element_blank())+
  theme(legend.justification = c(1, 1), legend.position = c(1, 1))+
  theme(legend.background = element_blank(),
        legend.key = element_blank())

enter image description here

I prefer using element_blank() which will remove a theme element as opposed to setting it to transparent and leaving it there. I've found depending on the graphics device the transparent can be interpreted differently.

Nate
  • 10,361
  • 3
  • 33
  • 40