Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

r - ggplot2 increase space between legend keys

How can I increase the space between the keys of the legend of ggplot2 plot?

library(ggplot2)
ggplot(aes(mpg, wt, colour = factor(cyl)),
       , data = mtcars) +
      geom_point() +
  theme(legend.direction = "horizontal", 
        legend.position = "bottom") +
  guides(color = guide_legend(nrow=2))

enter image description here

I am looking for a ggplot2 option that add a kind of vertical adjustment between (key 4 and key 6) in the plot above? Should I create a custom legend key?

PS: I want to increase the blank space between boxes not between labels.

the desired plot is :

enter image description here

NOTE: No the question is not duplicated of the other question. We want here to add a vertical spacing between items that are already in multiple rows. In the other question we have 1-row legend and we want to add spaces (horizontal) between items.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An alternative (and probably easier) solution is using legend.key and legend.key.size in the theme part of your code:

ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() +
  guides(color = guide_legend(nrow = 2)) +
  theme(legend.direction = 'horizontal', 
        legend.position = 'bottom',
        legend.key = element_rect(size = 5),
        legend.key.size = unit(1.5, 'lines'))

this gives:

enter image description here


In case you are calling theme_bw or theme_classic before manipulating the legend, you should set the color of the legend rectangle:

legend.key = element_rect(size = 5, color = 'white') #or: color = NA

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...