通过 ggplot 中的多个方面进行一次回归

One regression through multiple facets in ggplot

我正在尝试通过具有 20 个面的图形来拟合线性回归(实际上有 9 个)。每次我拟合回归(使用 geom_smooth 使用 method = lm),它拟合 20 条线,每个面一条,但是我希望每个 ReefSpecies 组合的一条线穿过所有 20 个面。

这是我的数字:

Similar Figure

这是我目前的情况:

Biomass <- c(20, 10, 5, 4, 5, 7, 8, 22, 13, 13, 15, 18, 2, 5, 7, 10)
Season <- c("Winter", "Spring", "Summer", "Fall")
Year <- c("1", "2", "3", "4")
ReefSpecies <- c("Admiral Ma", "Jaap Mf", "Grecian Ma", "Alligator Mf", "Jaap Mf", "Grecian Ma", "Alligator Mf", "Admiral Ma", "Grecian Ma", "Alligator Mf", "Admiral Ma", "Jaap Mf", "Alligator Mf", "Admiral Ma", "Jaap Mf","Grecian Ma")
Seasonal <- data.frame(Biomass, Season, Year, ReefSpecies)

testp <- ggplot(data = Seasonal, aes(x = Season, y = Biomass, group =        ReefSpecies, fill = ReefSpecies, colour = ReefSpecies))
testp <- testp + geom_point(stat = "identity", position="identity", inherit.aes = TRUE)
testp <- testp + facet_grid(. ~ Year, scales="fixed")
testp <- testp + theme(axis.text.x = element_text(angle = 90))
testp <- testp + theme(panel.margin.x = unit(0, "lines"))
testp <- testp + theme(legend.position = "top")
testp

根据评论,您想要place an identical smooth on each facet of a ggplot (which you can do by setting the faceting variable to NULL in the smooth

做的 想要的是对所有方面进行单一回归。我认为如果不进行一些黑客攻击 ,这是不可能的。你可以试试。

但是,我建议您退后一步,考虑一下为什么要这样做以及顺利意味着什么。也许这意味着分面不是正确的选择?在这种情况下,您可能会考虑定义一个 Time 变量来说明跨年的季节并对其进行回归(不带分面)。

一个示例(使用调整后的数据,因为您的示例数据每年没有超过一次观察):

Year <- sort(rep(Year, 4))
Seasonal <- data.frame(Biomass, Season, Year, ReefSpecies)
Seasonal$Time <- interaction(Season, Year)

ggplot(Seasonal, aes( Time,  Biomass, color=ReefSpecies)) + 
  geom_point() +
  geom_smooth(aes(group=ReefSpecies), method="lm")