如何改变ggplot2中图例项目之间的间距(附代码示例)

2,690 阅读2分钟

你可以使用以下方法来改变ggplot2中图例项目之间的间距。

方法1:改变水平间距

p +
  theme(legend.spacing.x = unit(1, 'cm'))

方法2:改变垂直间距

p +
  theme(legend.spacing.y = unit(1, 'cm')) +
  guides(fill = guide_legend(byrow = TRUE))

下面的例子展示了如何在以下数据框架中实际使用每种方法:

#create data frame
df <- data.frame(team=c('Mavs', 'Heat', 'Nets', 'Lakers', 'Suns', 'Cavs'),
                 points=c(24, 20, 34, 39, 28, 29),
                 assists=c(5, 7, 6, 9, 12, 13))

#view data frame
df

    team points assists
1   Mavs     24       5
2   Heat     20       7
3   Nets     34       6
4 Lakers     39       9
5   Suns     28      12
6   Cavs     29      13

例1:改变图例项之间的水平间距

下面的代码显示了如何在ggplot2中创建一个具有默认间距的水平图例的散点图:

library(ggplot2)

#create scatterplot with default spacing in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size=3) +
  theme(legend.position='bottom')

为了增加图例中各项目之间的水平间距,我们可以使用legend.spacing.x参数:

library(ggplot2)

#create scatterplot with increased horizontal spacing in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size=3) +
  theme(legend.position='bottom',
        legend.spacing.x = unit(1, 'cm'))

ggplot2 increased horizontal spacing between legend items

请注意,图例中的项目之间的水平间距已经增加。

你在unit()函数中使用的值越大,项目之间的间距就越大。

例2:改变图例项目之间的垂直间隔

下面的代码显示了如何在ggplot2中创建一个具有默认间距的垂直图例的散点图:

library(ggplot2)

#create scatterplot with default spacing in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size=3)

为了增加图例中各项目之间的垂直间距,我们可以使用legend.spacing.y参数:

library(ggplot2)

#create scatterplot with increased vertical spacing in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size=3) +
  theme(legend.spacing.y = unit(1, 'cm')) +
  guides(fill = guide_legend(byrow = TRUE))

ggplot2 increase vertical spacing between legend items

请注意,图例中的项目之间的垂直间距已经增加。

你在unit()函数中使用的值越大,项目间的间距就越大。

注意:我们必须包括使用byrow = TRUE参数的最后一行,否则图例中的项目将不会有预期的间距。

其他资源

下面的教程解释了如何在ggplot2中执行其他常见操作:

如何在ggplot2中改变图例标题
如何在ggplot2中改变图例大小
如何在ggplot2中改变图例位置