This is a follow up query to this query:
It was made using this code:
library(ggplot2)
df <- data.frame(x = sample(c("A", "B","C", "D"), 100, replace = TRUE),
y = as.factor(sample(c("North", "South", "West", NA), 100, replace = TRUE)))
ggplot(df)
aes(x, fill = y, color ="")
geom_bar()
scale_fill_manual(values = c("red",
"green",
"blue"),
na.value = "black" )
scale_color_manual(labels="Special value",values="black")
guides(fill = guide_legend(order=1),color = guide_legend(title = "", order=2,override.aes = list(fill="white")))
I wish to make the 2 legends appear as if they were levels of one legend.
To do this I wish to make the space between the 2 legends = the space between the keys in the legend on top.
My queries are:
- How do I find out how much space is there by default between the keys in the legend on top.
- How do I then modify the space between 2 legends to be equal to the answer of 1.
My research so far: I think I need theme(legend.spacing.y) for the second legend.
CodePudding user response:
I might be wrong, but I understand the following from
We can see that there is a problem with the title, fortunately we can get rid of it with title=NULL
in guides
. By removing it the space between the keys drops to 17 pts.
ggplot(df)
aes(x, fill = y, color ="")
geom_bar()
scale_fill_manual(values = c("red",
"green",
"blue"),
na.value = "black" )
scale_color_manual(labels="Special value",values="black")
guides(fill = guide_legend(order=1),color = guide_legend(title = NULL, order=2,override.aes = list(fill="white")))
theme(legend.key = element_rect(size = unit(0.5, 'pt'), color = "purple"),
legend.margin = margin(-17,0,0,0,unit="pt"))
Finally, we want to recreate the 0.5pt space between our keys :
ggplot(df)
aes(x, fill = y, color ="")
geom_bar()
scale_fill_manual(values = c("red",
"green",
"blue"),
na.value = "black" )
scale_color_manual(labels="Special value",values="black")
guides(fill = guide_legend(order=1),color = guide_legend(title = NULL, order=2,override.aes = list(fill="white")))
theme(legend.margin = margin(-16.5,0,0,0,unit="pt"))