【问题标题】:ggplot2: What controls the size of the point in the legend when size is a mapped aesthetic?ggplot2:当大小是​​映射美学时,什么控制图例中点的大小?
【发布时间】:2019-01-05 15:39:18
【问题描述】:

当您同时拥有线型和形状美学(分别使用 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") 

给予:

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

有没有什么方法可以改变图例中点的大小以达到形状/颜色的美感?

【问题讨论】:

  • 您可以在某些比例尺中使用override.aes,尽管我很难在同一个图例中获得一个大小的点和另一个大小的线。或者,如果您只想在图例中显示点,您可以在 geom_line / geom_path 中使用 show.legend = F

标签: r ggplot2


【解决方案1】:

我使用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"))

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    相关资源
    最近更新 更多