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

ogw*_*ogw 12 r ggplot2

我如何申请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)
Run Code Online (Sandbox Code Playgroud)

Hub*_*rtL 13

你必须将所有变量放在ggplot中aes():

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)))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Ben*_*ker 5

将映射添加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))
Run Code Online (Sandbox Code Playgroud)

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)))
Run Code Online (Sandbox Code Playgroud)

formula始终以x和表示y,无论原始数据集中调用了什么变量:

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

该模型分别适合数据中的组(Species)。

如果添加将具有相同效果的颜色映射(针对因子变量)(根据用于区分几何的所有映射的交集来隐式定义组),则将对线条进行适当的着色。

  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)))
Run Code Online (Sandbox Code Playgroud)

正如@HubertL指出的那样,如果您想对所有几何都应用相同的美学,则可以将它们放在原始ggplot调用中...

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

  • 您能否详细说明 a 和 b 的定义位置?这三个变量是 x=Sepal.Length, y = Petal.Length,color = Species。但是,公式是 y ~ a * x + b。如何指定物种是一个? (2认同)