R语言 有没有办法改变ggplot2中图例项之间的间距?

7vhp5slm  于 2023-04-27  发布在  其他
关注(0)|答案(8)|浏览(551)

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

legend.position ="top"

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

b5lpy0ml

b5lpy0ml1#

2018年7月发布的ggplot2 v3.0.0具有修改legend.spacing.xlegend.spacing.ylegend.text的工作选项。
更新2021年12月-要使legend.spacing.y工作,您需要在相应的guide_legend. See also this thread中设置byrow = TRUE。示例如下。

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

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_xxxguide_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函数。有关详细信息,请参阅issue

# 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)

kcwpcxri

kcwpcxri2#

我认为最好的选择是在guides中使用guide_legend

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

注意使用了default.unit,不需要加载grid包。

flseospp

flseospp3#

我用来在水平图例中添加空格的一个简单解决方案,只需在标签中添加空格(参见下面的摘录):

scale_fill_manual(values=c("red","blue","white"),
                    labels=c("Label of category 1          ",
                             "Label of category 2          ",
                             "Label of category 3"))
4xy9mtcn

4xy9mtcn4#

要在图例中的条目之间添加间距,请调整主题元素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
[Note关于编辑:当这个答案第一次发布时,有一个bug。这个bug现在已经被修复了]

vm0i2vca

vm0i2vca5#

现在optsggplot2包中被弃用,应该使用函数theme

library(grid) # for unit()
... + theme(legend.key.height=unit(3,"line"))
... + theme(legend.key.width=unit(3,"line"))
mbzjlibv

mbzjlibv6#

看起来最好的方法(在2018年)是在theme对象下使用legend.key.size

#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重新分层。
ftf50wuq

ftf50wuq7#

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

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

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

kwvwclae

kwvwclae8#

使用这些中的任何一个

legend.spacing = unit(1,"cm")
legend.spacing.x = unit(1,"cm")
legend.spacing.y = unit(1,"cm")

相关问题