如何使用多重美学更改图例大小/增加R中图例内变量之间的间距

如何使用多重美学更改图例大小/增加R中图例内变量之间的间距,r,ggplot2,legend-properties,aesthetics,R,Ggplot2,Legend Properties,Aesthetics,我的问题有两部分。下面我提供了使用ggplot创建代表性绘图的示例数据和代码 structure(list(x = c(2.93131952459005, 3.21275054434318, 1.36466997175509, 2.13626543532502, 1.45889556823722, 1.94598707699052, 0.719062322132357, 2.38139571953234, 2.37813367615963, 3.98126576880209), y = c(

我的问题有两部分。下面我提供了使用ggplot创建代表性绘图的示例数据和代码

structure(list(x = c(2.93131952459005, 3.21275054434318, 1.36466997175509, 
2.13626543532502, 1.45889556823722, 1.94598707699052, 0.719062322132357, 
2.38139571953234, 2.37813367615963, 3.98126576880209), y = c(7.51581380181603, 
9.77495763943671, 8.9666894018554, 8.62675858853528, 7.89238665417542, 
9.84865061237773, 7.24526820962333, 7.64727218939944, 7.28026738945878, 
8.6913070524479), z = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 
3L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor"), z2 = structure(c(1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("cat", "dog"), class = "factor")), class = "data.frame", row.names = c(NA, 
-10L))
第1部分:存在多个外观时更改图例大小

当您查看生成的图形时,图例中的项目z有两种与之相关的美学:颜色和形状。但是,它指的是线条颜色,而不仅仅是点颜色/形状。我想知道是否有一种方法可以增加z点的大小(仅在图例中),同时保持z中的线条大小不变。我尝试了使用size作为参数的
override.aes()
,但这会增加点和线的大小

第2部分:增加图例中变量之间的间距


这应该很简单,但我还没有找到一个简单的答案。在图例中,z和z2显然是独立的组件,但有没有办法增加这些变量之间的空间作为一个整体?我不是说像在
legend.spacing.x
中那样增加每个变量的每个级别之间的间距。基本上,我希望z中的“c”和z2的标题之间有更多的空格。

要回答您的第一部分问题,请参阅FILUP21对以下SO问题的回答。本质上,您需要使用以下代码更改底层网格美学

# Make JUST the legend points larger without changing the size of the legend lines:
# To get a list of the names of all the grobs in the ggplot
g
grid::grid.ls(grid::grid.force())

# Set the size of the point in the legend to 2 mm
grid::grid.gedit("key-[-0-9]-1-1", size = unit(4, "mm"))

# save the modified plot to an object
g2 <- grid::grid.grab()
ggsave(g2, filename = 'g2.png')
#仅使图例点变大,而不更改图例线的大小:
#获取ggplot中所有Grob的名称列表
G
grid::grid.ls(grid::grid.force())
#将图例中点的大小设置为2 mm
grid::grid.gedit(“键-[-0-9]-1-1”,大小=单位(4,“mm”))
#将修改后的打印保存到对象

g2非常有用,当然第2部分是一个简单的更改。你知道如何从grid.ls和grid.force中找到正确的grob吗?在您给出的示例中,参数为“key–[0–9]–1–1”,不在我的绘图中。我不确定命名约定如何工作。但是,在您的示例中,形状/点被命名为“键-1-3-…”、键-1-7-…”和键-1-11-…”。因此,如果我们对多位数数字“[0-9]+”使用正则表达式,我们可以通过以下方式编辑形状/点的大小:
grid::grid.gedit(“key-1-[-0-9]+-1.2-[-0-9]+-2-[-0-9]+,size=unit(5,“mm”)
有没有办法将其作为一个数字保存在r中?似乎一旦我保存到g2,我就不能再像ggplot那样处理这个对象了。保存到我的目录很好,但如果我想使用plot_grid、grid.arrange等将此新图例作为常用图例与另一个绘图合并,该怎么办?
# Make JUST the legend points larger without changing the size of the legend lines:
# To get a list of the names of all the grobs in the ggplot
g
grid::grid.ls(grid::grid.force())

# Set the size of the point in the legend to 2 mm
grid::grid.gedit("key-[-0-9]-1-1", size = unit(4, "mm"))

# save the modified plot to an object
g2 <- grid::grid.grab()
ggsave(g2, filename = 'g2.png')