使用 geom_smooth 从多个条件创建多行?

Use geom_smooth to create multiple lines from multiple criteria?

我正在尝试根据条件 1 创建多条具有相同线型的平滑线,并根据条件 2 为每条线分配不同的颜色。我在 Whosebug 中查看了各种类似的问题(如 , this, this),但它们所有这些都基于单一标准而不是两个标准。我尝试了不同的方法,但没有得到完整的结果。不同的做法及其结果如下:

方法一:

data(mtcars)
p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl))) +
  geom_point() + 
  geom_smooth( aes(group = as.factor(carb)),method ="lm", se = F, fullrange = T, alpha = .15, linetype = "dashed") 
p

结果是:

点的颜色正确且线型单一。但是,行数和颜色是错误的。我希望线条根据“cyl”值具有红色、蓝色或绿色。

方法二: 我尝试的第二种方法给了我正确的线数和颜色,但每条线都有不同的线型。

p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl), linetype = as.factor(carb))) +
  geom_point() + 
  geom_smooth( method ="lm", se = F, fullrange = T, alpha = .15) 
p

方法三: 在方法 III 中,结果与方法 I 相似。

p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl), group = as.factor(carb), linetype = "dashed")) +
  geom_point() + 
  geom_smooth( method ="lm", se = F, fullrange = T, alpha = .15) 
p

简而言之,方法 II 让我最接近 objective。现在,如何在方法二中获得单一线型?

在此先感谢您的帮助!

我会建议下一个方法,格式化线型:

library(ggplot2)
#Data
data(mtcars)
#Plot
p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl), linetype = as.factor(carb))) +
  geom_point() + 
  geom_smooth( method ="lm", se = F, fullrange = T, alpha = .15) 
p + scale_linetype_manual(values = rep('solid',length(unique(mtcars$carb))))

输出: