在ggplot中显示多条趋势线

时间:2019-04-10 05:13:14

标签: r ggplot2 trendline

我有一张桌子,

    id    | membership |   month    |   year     |   numberofXPurchased
----------+------------+------------+------------+-------------------
     1    |    05      |    02      |   2014     |          5
     1    |    06      |    03      |   2014     |          7     
     1    |    07      |    04      |   2014     |          3
     2    |    01      |    11      |   2014     |          2
     2    |    02      |    12      |   2014     |          1
     2    |    03      |    01      |   2015     |          4

我使用ggplot创建了折线图,以确定会员资格期限与购买X的次数之间的相关性

ggplot(data = df, aes (x = memberMonths, y=numberofXPurchased, group=id, color = id)) +
geom_line() +
geom_point() + 
theme(legend.position = "none") +
labs(y="Membership in Months", x = "X purchased")

这将产生一个预期的折线图,但是由于我有超过100000行数据,该图无法解释。因此,我试图仅显示趋势线,而不显示代表每个id的线,其中1条趋势线代表整个图表,以及每个'年'的一组趋势线(也许在另一个图表中)。

添加

stat_smooth( method="lm") or
geom_smooth(method = "lm")

仅将趋势线添加到现有绘图中,但是我想要趋势线而不是df中的数据

有没有一种有效的方法来完成此操作,请先谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用geom_smooth(),通过'lm'选项提供线性模型

import shapeless.syntax.std.tuple._
object toValidatedNel extends Poly1 {
  implicit def cse[A, B, AA >: A]: Case.Aux[Either[A, B], ValidatedNel[AA, B]] = at(_.toValidatedNel[AA])
}

(x1, x2, x3)
  .map(toValidatedNel)
  .tupled
  .toEither

显示您的代码看起来像..

geom_smooth(method = "lm")

ggplot(data = df, aes (x = memberMonths, y=numberofXPurchased,group=id, color = id)) + geom_smooth(method = "lm") + geom_point() + theme(legend.position = "none") + labs(y="Membership in Months", x = "X purchased") 似乎需要geom_smooth()来给出正确的趋势线,我将在geom_point()调用中使用alpha=0

geom_point()