150

有没有办法改变ggplot2中图例项之间的间距?我目前有

legend.position ="top" 

它会自动生成一个水平图例。但是,项目的间距非常接近,我想知道如何将它们分开更远。

4

8 回答 8

127

ggplot2 v3.0.02018 年 7 月发布的工作选项有修改legend.spacing.x和.legend.spacing.ylegend.text

2021 年 12 月更新 - 要开始legend.spacing.y工作,您需要byrow = TRUE在相应的 guide_legend 中进行设置。另请参阅此线程。下面的例子。

示例:增加图例键之间的水平间距

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(1.0, 'cm'))

注意:如果您只想扩大图例文本右侧的间距,请使用stringr::str_pad()

示例:增加垂直间距 (mind byrow = TRUE)

library(ggplot2)

ggplot(mtcars, aes(y = factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  theme(legend.spacing.y = unit(1.0, 'cm'))  +
  ## important additional element
  guides(fill = guide_legend(byrow = TRUE))

示例:将图例键标签移动到底部并增加垂直间距

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(1.0, 'cm'),
        legend.text = element_text(margin = margin(t = 10))) +
  guides(fill = guide_legend(title = "Cyl",
                             label.position = "bottom",
                             title.position = "left", title.vjust = 1)) 

示例:对于scale_fill_xxx&guide_colorbar

ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(fill = hp), pch = I(21), size = 5)+
  scale_fill_viridis_c(guide = FALSE) +
  theme_classic(base_size = 14) +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(0.5, 'cm'),
        legend.text = element_text(margin = margin(t = 10))) +
  guides(fill = guide_colorbar(title = "HP",
                               label.position = "bottom",
                               title.position = "left", title.vjust = 1,
                               # draw border around the legend
                               frame.colour = "black",
                               barwidth = 15,
                               barheight = 1.5)) 


以下已过时,但留给好奇的人。

对于垂直图例,设置legend.key.size只会增加图例键的大小,而不是它们之间的垂直空间

ggplot(mtcars) +
  aes(x = cyl, fill = factor(cyl)) +
  geom_bar() +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.key.size = unit(1, "cm"))

为了增加图例键之间的距离,legend-draw.r需要修改函数。有关更多信息,请参阅此问题

# function to increase vertical spacing between legend keys
# @clauswilke
draw_key_polygon3 <- function(data, params, size) {
  lwd <- min(data$size, min(size) / 4)
  
  grid::rectGrob(
    width = grid::unit(0.6, "npc"),
    height = grid::unit(0.6, "npc"),
    gp = grid::gpar(
      col = data$colour,
      fill = alpha(data$fill, data$alpha),
      lty = data$linetype,
      lwd = lwd * .pt,
      linejoin = "mitre"
    ))
}

### this step is not needed anymore per tjebo's comment below
### see also: https://ggplot2.tidyverse.org/reference/draw_key.html
# register new key drawing function, 
# the effect is global & persistent throughout the R session
# GeomBar$draw_key = draw_key_polygon3

ggplot(mtcars) +
  aes(x = cyl, fill = factor(cyl)) +
  geom_bar(key_glyph = "polygon3") +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.key = element_rect(color = NA, fill = NA),
        legend.key.size = unit(1.5, "cm")) +
  theme(legend.title.align = 0.5)

于 2018-05-31T02:39:23.513 回答
78

我认为最好的选择是使用guide_legendwithin guides

p + guides(fill=guide_legend(
                 keywidth=0.1,
                 keyheight=0.1,
                 default.unit="inch")
      )

注意使用default.unit,无需加载grid包。

于 2015-07-15T06:03:59.647 回答
46

我用来在水平图例中添加空格的简单修复,只需在标签中添加空格(请参阅下面的摘录):

  scale_fill_manual(values=c("red","blue","white"),
                    labels=c("Label of category 1          ",
                             "Label of category 2          ",
                             "Label of category 3"))
于 2015-03-07T14:45:45.340 回答
40

要在图例中的条目之间添加间距,请调整主题元素的边距legend.text

在每个图例标签的右侧添加 30pt 的空间(可能对水平图例有用):

p + theme(legend.text = element_text(
    margin = margin(r = 30, unit = "pt")))

在每个图例标签左侧添加 30pt 的空间(可能对垂直图例有用):

p + theme(legend.text = element_text(
    margin = margin(l = 30, unit = "pt")))

对于一个ggplot2对象p。关键字是legend.textmargin

[关于编辑的注意事项:首次发布此答案时,存在错误。该错误现已修复]

于 2017-03-21T22:36:01.313 回答
38

Now that opts is deprecated in ggplot2 package, function theme should be used instead:

library(grid) # for unit()
... + theme(legend.key.height=unit(3,"line"))
... + theme(legend.key.width=unit(3,"line"))
于 2014-11-17T11:29:51.360 回答
24

看起来最好的方法(2018 年)是legend.key.sizetheme对象下使用。(例如,见这里)。

#Set-up:
    library(ggplot2)
    library(gridExtra)

    gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
        geom_point()

如果您使用的是,这真的很容易theme_bw()

  gpbw <- gp + theme_bw()

#Change spacing size:

  g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
  g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
  g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1bw,g2bw,g3bw,nrow=3)

在此处输入图像描述

但是,否则效果不太好(例如,如果您需要图例符号上的灰色背景):

  g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
  g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
  g3 <- gp + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1,g2,g3,nrow=3)

#Notice that the legend symbol squares get bigger (that's what legend.key.size does). 

#Let's [indirectly] "control" that, too:
  gp2 <- g3
  g4 <- gp2 + theme(legend.key = element_rect(size = 1))
  g5 <- gp2 + theme(legend.key = element_rect(size = 3))
  g6 <- gp2 + theme(legend.key = element_rect(size = 10))

  grid.arrange(g4,g5,g6,nrow=3)   #see picture below, left

请注意,白色方块开始阻挡图例标题(如果我们不断增加值,最终会阻挡图形本身)。

  #This shows you why:
    gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))

在此处输入图像描述

我还没有找到解决上述问题的解决方法...如果您有任何想法,请在评论中告诉我,我会相应地更新!

  • 我想知道是否有某种方法可以使用$layers...
于 2018-05-29T22:40:19.160 回答
17

来自 Koshke 在 ggplot2 上的工作和他的博客(Koshke 的博客

... + theme(legend.key.height=unit(3,"line")) # Change 3 to X
... + theme(legend.key.width=unit(3,"line")) # Change 3 to X

在控制台中输入theme_get()以查看其他可编辑的图例属性。

于 2012-07-06T18:36:42.353 回答
5

使用其中任何一个

legend.spacing = unit(1,"cm")
legend.spacing.x = unit(1,"cm")
legend.spacing.y = unit(1,"cm")
于 2017-11-26T09:30:02.857 回答