Home > Mobile >  ggplot legend.box.background produces strange relics
ggplot legend.box.background produces strange relics

Time:01-25

This is a bit harder to explain than notice the bottom right corner!!!

I managed to produce a similar error with the iris dataset where legend.box.background is only partially drawn.

data(iris)

ggplot(iris) theme_classic() 
  geom_point(aes(x=Petal.Length, y=Sepal.Length, color=Species, size=Sepal.Width)) 
  scale_color_manual(name=NULL, values=c("red","green","blue") ,labels=c("supersupersupersuperlong", "test2", "test3")) 
  theme(legend.position=c(0.1,0.75),legend.box.background=element_rect(fill="white", color="black"), legend.spacing.y=unit(0,"cm"))



UPDATE

I noticed in my original example it had to do with text length, so I tried adding a space after some of the labels which changes the "arrangement" of the twice-drawn lines a little bit. But I can't find an arrangement of whitespace that makes it go away completely. Anyone know how to manually change the size of the legend.box.background. If not I will draw a geometric rectangle and call it quits.

CodePudding user response:

I think the problem here is that the legend.background (which is a white rectangle behind each component of your legend), is partially drawing over the line surrounding the legend.box, which is the rectangle surrounding the whole legend. You can simply remove the legend.background

For example, your plot goes from this:

ggplot(iris)   
  theme_classic()  
  geom_point(aes(x = Petal.Length, y = Sepal.Length, color = Species, 
                 size = Sepal.Width))  
  scale_color_manual(name = NULL, values = c("red", "green", "blue"),
                     labels = c("supersupersupersuperlong", "test2", "test3"))  
  theme(legend.position = c(0.1, 0.75),
        legend.box.background = element_rect(fill = "white", color = "black"), 
        legend.spacing.y = unit(0, "cm"))

enter image description here

To this:

ggplot(iris)   
  theme_classic()  
  geom_point(aes(x = Petal.Length, y = Sepal.Length, color = Species, 
                 size = Sepal.Width))  
  scale_color_manual(name = NULL, values = c("red", "green", "blue"),
                     labels = c("supersupersupersuperlong", "test2", "test3"))  
  theme(legend.position = c(0.1, 0.75),
        legend.background = element_blank(),
        legend.box.background = element_rect(fill = "white", color = "black"), 
        legend.spacing.y = unit(0, "cm"))

enter image description here

  •  Tags:  
  • Related