如何使用 plotly 将多个 traces/trendlines 每个都带有数据子集添加到 R 中的单个散点图上

How do I add multiple traces/trendlines each with a subset of data onto a single scatterplot in R using plotly

plotly包中,我使用了ggplot()函数和ggplotly()函数。我想用 x 轴上的 CWD 数量和 y 轴上的 Lawn 数量创建一个散点图。每个散点图应该有三条线来反映每年的线性关系(2013 年、2014 年、2015 年)。 Lawn 每年有 10 分,CWD 有 10 分。作为我的数据样本如下:

    Year CWD Lawn
 1  2013   0  420
 2  2013   6  390
 3  2013  14  410
 4  2013  12  349
 5  2013   3  348
 6  2013  46  354
 7  2013 121  311
 8  2013  56  381
 9  2013  42  386
 10 2013  26  381
 11 2014   2  121
 12 2014   2  163
 13 2014   3  298

这是我使用的代码:

library(plotly)

### Amount of Lawn versus Amount of CWD
fit<-lm(Lawn~CWD,data=data)
lawn <- ggplot(data, aes(x=CWD, y=Lawn, colour=Year)) + geom_point()
ggplotly()
add_trace(data=data, x = CWD, y = fitted(fit), mode = "lines")

我知道上面的代码是不正确的,因为它只适合图表中的一条线而不考虑年份。我曾尝试使用 geom_abline 但我不知道如何在此函数中提取数据子集。见下文:

那么首先,我如何绘制三个轨迹(每年一个)?我应该每年将我的数据以单独的 .csv 文件导入 R 中吗?当然,在代码中有一种更简单的方法可以做到这一点。 其次,如何改变点和线的颜色?

最简单的方法是在 ggplot 内,使用 geom_smooth 为您做回归:

lawn <- ggplot(dat, aes(x=CWD, y=Lawn, colour=factor(Year))) + 
  geom_point() +
  geom_smooth(method = 'lm', se = FALSE)

请注意,我将数据命名为 dat,因为 data 是 R 中的一个函数。

有你样本数据:

关于颜色,看看?scale_colour_discrete