r - 有没有办法在 scale_discrete_manual 中定义多种美学?

标签 r ggplot2

我正在浏览 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_manualvalues 映射到所有美学,而 “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/

相关文章:

r - 函数内 ggplot2 的惰性求值

r - 基于条件的部分粗体ggplot2指南标签

r - Shiny 的应用程序中的多个 group_by

r - R中可变数量的for循环

R ggmap (qmap) map 类型错误 = 'watercolor'

r - 在 R 中使用 ggplot 更改图例的一部分?

r - 使用表情符号的 ggplot 图例

python - 在数据框的单个列上进行 Pandas 逻辑索引以分配值

r - 如何使用 gg密度 叠加总密度和组密度

r - R 初学者 - 表操作基础