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")
给出:
很难说出符号如何映射到因子水平。我可以使线条不那么粗,但我当然可能不想这样做。如果我没有将 size 映射到wts
,我可以只使用 in 中的size
参数geom_point
。但是由于 size 被映射到wts
,所以无论线条大小是否已更改,图例对点形状的表示似乎都会退回到默认值。
有什么方法可以改变图例中点的大小以实现形状/颜色美学?
解决方案
我使用这篇文章作为指导 - 显然只能使用底层网格系统分别缩放点和线:
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"))
推荐阅读
- java - 为多个并行流更新一个计数器
- python - 使用python进行多项式加法
- configuration - 弹簧型材。配置数据库问题
- jquery - owl carousel 跳转到特定幻灯片并为其添加类
- javascript - React Native Wix 日历标记日期显示错误
- asp.net - 需要在 MVC 中渲染部分视图以代替具有相同布局的另一个部分视图
- python - 我需要为 python pandas 中的缺失索引插入空值
- node.js - webpack 配置文件中没有定义插件
- reactjs - React-select 在 Laravel-mix 中没有显示价值
- python - VSTS 上的私人代理未触发代理作业