Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One regression through multiple facets in ggplot

Tags:

r

ggplot2

facet

lm

I am trying to fit a linear regression (9 of them actually) through a figure that has 20 facets. Every time I fit the regression (using geom_smooth using method = lm), it fits 20 lines, one through each facet, however I would like the one line for each ReefSpecies combination to go through all 20 facets.

Here is my figure:

Similar Figure

Here is what I have so far:

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
like image 726
Danib90 Avatar asked Jun 18 '26 12:06

Danib90


1 Answers

Based on comments, you do not want to place an identical smooth on each facet of a ggplot (which you can do by setting the faceting variable to NULL in the smooth.

What you do want is to have a single regression across all facets. I think this isn't possible without some hacking like that shown here. You could try that.

But instead, I'd recommend stepping back to consider why you want to do it and what the smooth means. Perhaps it means facets aren't the right choice? In that case, you might consider defining a Time variable that accounts for seasons across years and regress on that (without facets).

An example (with tweaked data, because your example data does not have more than one observation per year):

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")

enter image description here

like image 171
jaimedash Avatar answered Jun 20 '26 02:06

jaimedash