Multiple linear regressions by factor in ggplot r

Viewed 1854

I would like to make 1 scatterplot with variables of different depths, and add individual linear regressions to each depth group. I'm struggling with the code in ggplot.

Here is the dput of my data (called "ro_aue"):

    structure(list(sample_id = 64:77, site = structure(1:14, .Label = c("ROA1-0", 
    "ROA1-30", "ROA1-60", "ROA1-90", "ROA2-0", "ROA2-30", "ROA3-0", 
    "ROA3-30", "ROA3-60", "ROA3-90", "ROA4-0", "ROA4-30", "ROA4-60", 
    "ROA4-90"), class = "factor"), field = structure(c(1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "RO", class = "factor"), 
        hole_number = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
        1L, 1L, 1L, 1L, 1L, 1L), .Label = "ROA", class = "factor"), 
        depth = c(1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 
        4L, 4L), co2_flux_µmol_c_m2_s1 = c(154.3338436, 282.1015066, 
        465.7342506, 554.0064102, 133.6499023, 300.5398639, 143.2820904, 
        379.3802332, 331.9730719, 265.3653557, 116.5290758, 417.7642772, 
        303.2152718, 409.3601595), soc_stock_kg_m2 = c(4.7, 2.5, 
        2.5, 0.3, 5.5, 2.2, 3.4, 1.8, 1, 0.4, 3.4, 0.6, 0.7, 0.6)), .Names = c("sample_id", 
    "site", "field", "hole_number", "depth", "co2_flux_µmol_c_m2_s1", 
    "soc_stock_kg_m2"), class = "data.frame", row.names = c(NA, -14L
    ))

using this code, I'm able to get a nice scatterplot:

    ggplot(data = ro_aue, aes(x = soc_stock_kg_m2, y = co2_flux_µmol_c_m2_s1)) +
      geom_point(size = 4, aes(color = factor(depth), shape = factor(depth))) +
      labs(x = lab_soc, y = lab_co2) +
      labs(color=legend_title, shape=legend_title) +
      ggtitle(expression('Rottenbuch Hole Campaign, CO'[2]*'')) + 
      geom_smooth(method=lm, se=FALSE, formula=y~x-1)

what I have

But what I really need is something like this:

what I need

Any help would be greatly appreciated!

0 Answers
Related