首页 > 解决方案 > 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") 

给出:

阴谋

很难说出符号如何映射到因子水平。我可以使线条不那么粗,但我当然可能不想这样做。如果我没有将 size 映射到wts,我可以只使用 in 中的size参数geom_point。但是由于 size 被映射到wts,所以无论线条大小是否已更改,图例对点形状的表示似乎都会退回到默认值。

有什么方法可以改变图例中点的大小以实现形状/颜色美学?

标签: rggplot2

解决方案


我使用这篇文章作为指导 - 显然只能使用底层网格系统分别缩放点和线:

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

输出: 在此处输入图像描述


推荐阅读