【问题标题】:One regression through multiple facets in ggplot通过 ggplot 中的多个方面进行一次回归
【发布时间】:2016-08-06 04:20:12
【问题描述】:

我试图通过一个有 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

【问题讨论】:

  • 请让您的问题可重现。
  • 在这方面,请提供一些数据,以便我们重现您的问题。
  • ggplotGrob 的东西和所有主题元素都与您的问题无关,只会让帖子看起来很困难。 geom_point() 里面的东西也是没必要的。我建议您使用任何线来拟合回归(stat_smooth 或其他东西?),您在该层内专门设置 group 美学。请注意,在您最初的 ggplot() 调用中,您如何设置将由所有其他层继承的分组和着色美学,除非您另有指定。你可以添加类似+geom_smooth(method = "lm", aes(group=1))
  • 编辑添加了一个小的模拟数据集!谢谢!
  • This question/answer 可能密切相关。

标签: r ggplot2 facet lm


【解决方案1】:

基于 cmets,您确实想要 place an identical smooth on each facet of a ggplot(您可以通过 setting the faceting variable to NULL in the smooth 完成。

想要的是在所有方面都有一个单一的回归。我认为如果没有一些黑客攻击like that shown here,这是不可能的。你可以试试。

但是,我建议您退后一步考虑一下您为什么要这样做以及平滑意味着什么。也许这意味着刻面不是正确的选择?在这种情况下,您可能会考虑定义一个 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")

【讨论】:

  • 抱歉措辞不好。在你的图中,我想要 4 条回归线,一条用于跨越 4 个方面的每个 ReefSpecies 组合
  • @aosmith 第一个链接似乎是我想要的,但如果我告诉你我知道该代码中发生了什么,我会撒谎。
  • 好的,来自@aosmith 评论问题的第一个链接?即stackoverflow.com/questions/31690007/…
  • 谢谢。很抱歉造成误解,也许改写问题以使清楚?第二句话有点长,虽然重读我明白你的意思。
  • 但是,最终您希望季节在每一年中具有不同的含义吗?我认为没有办法在 ggplot 中做到这一点,而无需通过gtable 或链接答案中的类似方式进行黑客攻击。
猜你喜欢
  • 2014-08-03
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
相关资源
最近更新 更多