首页 文章

如何为每个组应用geom_smooth()?

提问于
浏览
10

如何为每个组申请 geom_smooth()

下面的代码使用 facet_wrap() ,因此在单独的图中绘制每个组 .
我想整合图表,并获得一个图表 .

ggplot(data = iris, aes(x = Sepal.Length,  y = Petal.Length)) +
  geom_point(aes(color = Species)) +
  geom_smooth(method = "nls", formula = y ~ a * x + b, se = F,
              method.args = list(start = list(a = 0.1, b = 0.1))) +
  facet_wrap(~ Species)

2 回答

  • 4

    你必须将所有变量放在ggplot _2940026中:

    ggplot(data = iris, aes(x = Sepal.Length,  y = Petal.Length, color = Species)) +
      geom_point() +
      geom_smooth(method = "nls", formula = y ~ a * x + b, se = F,
                  method.args = list(start = list(a = 0.1, b = 0.1)))
    

    enter image description here

  • 7

    将映射 aes(group=Species) 添加到 geom_smooth() 调用将执行您想要的操作 .

    基本情节:

    library(ggplot2); theme_set(theme_bw())
      g0 <- ggplot(data = iris, aes(x = Sepal.Length,  y = Petal.Length)) +
            geom_point(aes(color = Species))
    

    geom_smooth

    g0 + geom_smooth(aes(group=Species),
                  method = "nls", formula = y ~ a * x + b, se = FALSE,
                  method.args = list(start = list(a = 0.1, b = 0.1)))
    

    formula 始终以 xy 表示,无论原始数据集中调用哪些变量:

    • 公式中的 x 变量是指映射到x轴的变量( Sepal.Length

    • y 变量为y轴变量( Petal.Length

    该模型单独安装到数据中的组( Species ) .

    如果添加具有相同效果的颜色映射(对于因子变量)(根据用于区分geoms的所有映射的交集隐式定义组),则行将适当地着色 .

    g0 + geom_smooth(aes(colour=Species),
                  method = "nls", formula = y ~ a * x + b, se = FALSE,
                  method.args = list(start = list(a = 0.1, b = 0.1)))
    

    正如@HubertL指出的那样,如果你想对所有的geoms应用相同的美学,你可以把它们放在原来的 ggplot 调用中......

    顺便说一句,我认为实际上你想要使用更复杂的 nls 模型 - 否则你可以使用 geom_smooth(...,method="lm") 并省去自己的麻烦......

相关问题