ggplot2:当大小是​​映射的美感时,什么控制图例中点的大小?

时间:2018-07-28 23:57:51

标签: r ggplot2

当您同时具有线型和形状美感时(分别使用geom_path和geom_point),有时可能很难在图例中找出点,因为它们与线重叠。

这是一个可行的例子。我有一个加权线性模型,想将预测数据与观测数据一起绘制。

iris$wts <- runif(nrow(iris), min = 0.2, max = 3) 
fitw <- lm(Petal.Length ~ Petal.Width * Species, data = iris, 
           weights = wts)

newdat <- data.frame(
  Petal.Width = rep(seq(from = min(iris$Petal.Width),
                        to = max(iris$Petal.Width), length.out = 100),
                    3),
  Species = c(rep("setosa", 100), rep("versicolor", 100), rep("virginica", 100))
)
newdat$Petal.Length <- predict(fitw, newdata = newdat)

library(ggplot2)
ggplot(data = newdat, aes(y = Petal.Length, x = Petal.Width,
                              colour = Species)) +
  geom_path(aes(linetype = Species), size = 1.1) +
  geom_point(data = iris, aes(x = Petal.Width, y = Petal.Length, shape = Species,
                              size = wts), show.legend = TRUE) +
  scale_shape_discrete(name = "Species") +
  scale_size_identity(guide = "none") 

礼物:

plot

很难说出这些符号是如何映射到因子水平的。我可以使线的厚度减小,但是当然我可能不想这样做。如果没有将大小映射到wts,则可以在size中使用geom_point参数。但是,因为大小已映射到wts,所以无论线径是否已更改,点形状的图例表示都似乎恢复为默认值。

是否可以通过任何方式更改图例中形状/颜色美观的点的大小?

1 个答案:

答案 0 :(得分:0)

我使用了this帖子作为指导-显然,只有使用基础网格系统才能分别缩放点和线:

library(ggplot2)
ggplot(data = newdat, aes(y = Petal.Length, x = Petal.Width,
                          colour = Species)) +
  geom_path(aes(linetype = Species), size = 1.1) +
  geom_point(data = iris, aes(x = Petal.Width, y = Petal.Length, shape = Species,
                              size = wts), show.legend = TRUE) + 
  scale_shape_discrete(name = "Species") +
  scale_size_identity(guide = "none")


library(grid)

grid.ls(grid.force())    # To get the names of all the grobs in the ggplot

# The edit - to set the size of the point in the legend to 4 mm
grid.gedit("key-3-1-2.4-2-4-2", size = unit(5, "mm"))
grid.gedit("key-4-1-2.5-2-5-2", size = unit(5, "mm"))
grid.gedit("key-5-1-2.6-2-6-2", size = unit(5, "mm"))

输出: enter image description here