我正在浏览 scale_discrete_manual ggplot 元素,我只能找到具有相同值的组合美学示例,例如填充和颜色,如下所示:
library(ggplot2)
data <- data.frame(x = 1:10, y = 1:10, group = factor(rep(1:2, length.out = 10)))
ggplot(data, aes(x = x, y = y, color = group, fill = group)) +
geom_line() +
scale_discrete_manual(c("color", "fill"), values = c("yellow", "darkred"))
但我找不到任何示例或说明是否可以对具有不同类型值(如颜色和线型)的美学执行相同的操作。
library(ggplot2)
data <- data.frame(x = 1:10, y = 1:10, group = factor(rep(1:2, length.out = 10)))
# It gives an error
ggplot(data, aes(x = x, y = y, color = group, linetype = group)) +
geom_line() +
scale_discrete_manual(c("color", "linetype"), values = c("yellow", "darkred", "solid", "dashed"))
我知道可以通过对 scale_discrete_manual
的 2 个单独调用或使用可以封装这些调用的自定义函数来完成我需要的操作,但我感兴趣的是是否可以只做同样的事情以 ggplot 方式原生调用 1 次?
更新
目前,我已经选择了自定义函数,它完全满足我的需要:
scale_discrete_manual_ext <- function(aesthetics, values, name)
{
lapply(aesthetics, function(aesthetic) {
ggplot2::scale_discrete_manual(aesthetic, values = values[[aesthetic]], name = name)
})
}
# Usage
ggplot(data, aes(x = x, y = y, color = group, linetype = group)) +
geom_line() +
scale_discrete_manual_ext(c("color", "linetype"), values = list(color = c("yellow", "darkred"),linetype = c("solid", "dashed")), name = "Legend name")
但是问题仍然悬而未决。
最佳答案
我想问题是,ggplot 试图将提供给 scale_discrete_manual
的 values
映射到所有美学,而 “solid”
没有颜色.
我看到的唯一解决方案是像这里一样使用单独的比例:
ggplot(data, aes(x = x, y = y, color = group, fill = group, linetype = group)) +
geom_line(size = 3) +
scale_discrete_manual(c("color", "fill"), values = c("yellow", "darkred")) +
scale_linetype_manual(values = c("dashed", "dotted"))
关于r - 有没有办法在 scale_discrete_manual 中定义多种美学?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66573161/