Search code examples
rggplot2regressionsubsetdata-fitting

Make a regression graph when two variables are in the same column


When the data is like below

    nitrogen=rep(c("N0","N1"), each=5)
    yield=c(10,12,15,16,18,22,20,18,19,22)
    dataA=data.frame(nitrogen,yield)
        
     nitrogen yield
       N0    10
       N0    12
       N0    15
       N0    16
       N0    18
       N1    22
       N1    20
       N1    18
       N1    19
       N1    22

if I want to fit yield for No and N1, how can I do that? Of course, I can transpose column to row, but my real data have more 30 columns, so if I transpose to column to rows, there will be lots of columns in data. So I want a simple code to fit N0 with N1 for yield.

Simply I thought like below

ggplot(data=dataA, aes(x=subset(dataA,nitrogen=="N0")$yield, y=subset(dataA,nitrogen=="N1")$yield)+
  stat_smooth(method='lm', linetype=1, se=FALSE, formula=y~x, 
              linewidth=0.5, color="dark red") +
  geom_point(alpha=0.5, size=4)

but it does not work.

Could you please let me know how to do that?

Always many thanks!!


Solution

  • We could pass vectors to x and y with subset:

    ggplot() +
      stat_smooth(aes(x = dataA[ dataA$nitrogen == "N0", "yield" ],
                      y = dataA[ dataA$nitrogen == "N1", "yield" ]),
                  method = "lm", linetype = 1, se = FALSE, 
                  formula = y ~ x, 
                  linewidth = 0.5, color = "dark red") +
      geom_point(aes(x = dataA[ dataA$nitrogen == "N0", "yield" ],
                     y = dataA[ dataA$nitrogen == "N1", "yield" ]),
                 alpha = 0.5, size = 4)
    

    enter image description here

    But I'd prefer to transpose the data before plotting:

    d <- data.frame(split(dataA$yield, dataA$nitrogen))
    
    ggplot(d, aes(x = N0, y = N1)) +
      stat_smooth(method = "lm", linetype = 1, se = FALSE, formula = y ~ x, 
                  linewidth = 0.5, color = "dark red") +
      geom_point(alpha = 0.5, size = 4)
    

    enter image description here