有没有办法改变ggplot2中图例项之间的间隔?

时间:2022-05-05 13:30:37

Is there a way to change the spacing between legend items in ggplot2? I currently have

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

legend.position ="top" 

which automatically produces a horizontal legend. However, the spacing of the items is very close together and I am wondering how to space them farther apart.

自动生成一个水平图例。然而,这些物品的间距非常接近,我想知道如何将它们分隔开。

8 个解决方案

#1


45  

I think the best option is to use guide_legend within guides:

我认为最好的选择是在指南中使用guide_legend:

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

Note the use of default.unit , no need to load grid package.

注意默认的用法。单元,无需加载网格包。

#2


36  

A simple fix that I use to add space in horizontal legends, simply add spaces in the labels (see extract below):

我用来在水平图例中添加空间的一个简单修复,就是在标签中添加空格(参见下面的摘录):

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

#3


30  

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

既然在ggplot2包中不建议使用opts,那么应该使用函数主题:

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

#4


10  

From Koshke's work on ggplot2 and his blog (Koshke's blog)

来自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

Type theme_get() in the console to see other editable legend attributes.

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

#5


9  

The way to add spacing between entries in a horizontal legend ought to be to adjust the margins of the theme element legend.text. For example, to add 24pt of space to the right of each legend label, for a ggplot object p:

在水平图例中添加条目间距的方法应该是调整主题元素legend.text的边界。例如,要在每个传奇标签的右边添加24pt空间,对于ggplot对象p:

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

Unfortunately, the above does not work, since legend.text does not respond to margin values passed to element_text (neither does legend.title). This is a known bug: https://github.com/tidyverse/ggplot2/issues/1502

不幸的是,以上这些都不管用,因为传说。文本不响应传递给element_text的边距值(勒名.title也不响应)。这是一个已知的bug: https://github.com/tidyverse/ggplot2/issues/1502

Until the bug is fixed, the simplest option for adding spacing between legend items seems to be to pad the labels themselves with spaces, as suggested by user2568648 and SaschaH.

在修复错误之前,添加图例项之间间隔的最简单选项似乎是用空格填充标签本身,如user2568648和SaschaH所建议的。

#6


4  

The upcoming version 2.3.0 of ggplot2 has options to modify legend.spacing.x, legend.spacing.y and legend.text.

ggplot2即将发布的2.3.0版本有修改传说空间的选项。x,legend.spacing。y和legend.text。

To install, run the following lines:

要安装,请运行以下代码行:

install.packages("devtools")
devtools::install_github("tidyverse/ggplot2")

Example: Increase horizontal spacing between legend keys

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

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_viridis_d("Cyl") +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(1.0, 'cm'))

有没有办法改变ggplot2中图例项之间的间隔?

Example: Move the legend key labels to the bottom and increase vertical spacing

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

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_viridis_d("Cyl") +
  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)) 

有没有办法改变ggplot2中图例项之间的间隔?

Example: scale_fill_xxx & guide_colorbar

例如: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(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,
                             label = TRUE,
                             draw.ulim = TRUE,
                             draw.llim = TRUE,
                             # draw border around the gradient legend
                             frame.colour = "black",
                             ticks = TRUE, 
                             barwidth = 15,
                             barheight = 1.5, 
                             direction = 'horizontal')) 

有没有办法改变ggplot2中图例项之间的间隔?

Created on 2018-05-30 by the reprex package (v0.2.0).

reprex包(v0.2.0)在2018-05-30创建的。

#7


1  

Use any of these

使用任何一种

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

#8


1  

Looks like the best approach (in 2018) is to use legend.key.size under the theme object. (e.g., see here).

看来最好的办法(2018年)是使用勒传。主题对象下的大小。(例如,见这里)。

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

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

This is real easy if you are using theme_bw():

如果您正在使用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)

有没有办法改变ggplot2中图例项之间的间隔?

However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):

然而,这并不是很好,否则(例如,如果你需要你的传奇符号的灰色背景):

  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

Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).

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

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

有没有办法改变ggplot2中图例项之间的间隔?

I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!

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

  • I wonder if there is some way to re-layer things using $layers...
  • 我想知道是否有什么方法可以用$layers来重新铺设东西……

#1


45  

I think the best option is to use guide_legend within guides:

我认为最好的选择是在指南中使用guide_legend:

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

Note the use of default.unit , no need to load grid package.

注意默认的用法。单元,无需加载网格包。

#2


36  

A simple fix that I use to add space in horizontal legends, simply add spaces in the labels (see extract below):

我用来在水平图例中添加空间的一个简单修复,就是在标签中添加空格(参见下面的摘录):

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

#3


30  

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

既然在ggplot2包中不建议使用opts,那么应该使用函数主题:

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

#4


10  

From Koshke's work on ggplot2 and his blog (Koshke's blog)

来自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

Type theme_get() in the console to see other editable legend attributes.

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

#5


9  

The way to add spacing between entries in a horizontal legend ought to be to adjust the margins of the theme element legend.text. For example, to add 24pt of space to the right of each legend label, for a ggplot object p:

在水平图例中添加条目间距的方法应该是调整主题元素legend.text的边界。例如,要在每个传奇标签的右边添加24pt空间,对于ggplot对象p:

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

Unfortunately, the above does not work, since legend.text does not respond to margin values passed to element_text (neither does legend.title). This is a known bug: https://github.com/tidyverse/ggplot2/issues/1502

不幸的是,以上这些都不管用,因为传说。文本不响应传递给element_text的边距值(勒名.title也不响应)。这是一个已知的bug: https://github.com/tidyverse/ggplot2/issues/1502

Until the bug is fixed, the simplest option for adding spacing between legend items seems to be to pad the labels themselves with spaces, as suggested by user2568648 and SaschaH.

在修复错误之前,添加图例项之间间隔的最简单选项似乎是用空格填充标签本身,如user2568648和SaschaH所建议的。

#6


4  

The upcoming version 2.3.0 of ggplot2 has options to modify legend.spacing.x, legend.spacing.y and legend.text.

ggplot2即将发布的2.3.0版本有修改传说空间的选项。x,legend.spacing。y和legend.text。

To install, run the following lines:

要安装,请运行以下代码行:

install.packages("devtools")
devtools::install_github("tidyverse/ggplot2")

Example: Increase horizontal spacing between legend keys

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

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_viridis_d("Cyl") +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(1.0, 'cm'))

有没有办法改变ggplot2中图例项之间的间隔?

Example: Move the legend key labels to the bottom and increase vertical spacing

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

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_viridis_d("Cyl") +
  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)) 

有没有办法改变ggplot2中图例项之间的间隔?

Example: scale_fill_xxx & guide_colorbar

例如: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(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,
                             label = TRUE,
                             draw.ulim = TRUE,
                             draw.llim = TRUE,
                             # draw border around the gradient legend
                             frame.colour = "black",
                             ticks = TRUE, 
                             barwidth = 15,
                             barheight = 1.5, 
                             direction = 'horizontal')) 

有没有办法改变ggplot2中图例项之间的间隔?

Created on 2018-05-30 by the reprex package (v0.2.0).

reprex包(v0.2.0)在2018-05-30创建的。

#7


1  

Use any of these

使用任何一种

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

#8


1  

Looks like the best approach (in 2018) is to use legend.key.size under the theme object. (e.g., see here).

看来最好的办法(2018年)是使用勒传。主题对象下的大小。(例如,见这里)。

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

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

This is real easy if you are using theme_bw():

如果您正在使用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)

有没有办法改变ggplot2中图例项之间的间隔?

However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):

然而,这并不是很好,否则(例如,如果你需要你的传奇符号的灰色背景):

  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

Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).

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

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

有没有办法改变ggplot2中图例项之间的间隔?

I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!

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

  • I wonder if there is some way to re-layer things using $layers...
  • 我想知道是否有什么方法可以用$layers来重新铺设东西……