Maria
Maria

Reputation: 243

How to plot several regression lines in same scatter plot in R?

I have a dataframe with data of body temperature (Tb), substrate temperature (Ts) for several individuals of both sexes and comming from three different populations like this: (I made up this table since I couldn't manage to share my full table, but I have around 30 individuals from each pop)

pop  sex  tb  ts
bo    m     37   30
bo    m     39   29
bo    f     36   36
pa    m     40   34
pa    f     37   28
pa    m     37   33
pa    f     36   26
re    f     35   24
re    f     37   29
re    m     38   30

I want to assess the relationship between Tb and Ts but not only for the species but for each population separately in order to identify possible differences in slopes among them.

my.regression <- lm(tb ~ ts*pop*sex, data = mydata)

I managed to plot a scatter plot with different colors, one byeach of my populations. However, I couldn't plot my regressions lines. I searched for answers everywhere: about how to add the regression lines by group...(not in stackoverflow, not even with the help of almighty google, youtube tutorials, R book, R graphics books and so on)

All I want is to plot one regression line by each population. Something similar to this plot

Upvotes: 3

Views: 27600

Answers (1)

David Robinson
David Robinson

Reputation: 78590

This is easy to do using ggplot2 and a geom_smooth layer:

library(ggplot2)
ggplot(mydata, aes(x=tb, y=ts, col=pop)) + geom_point() +
            geom_smooth(method="lm", se=FALSE)

If you want to separate by sex as well, then as suggested by @Henrik you might want to try placing them in separate subgraphs (called facets):

ggplot(mydata, aes(tb, ts, col=pop)) + geom_point() +
             geom_smooth(method="lm", se=FALSE) + facet_wrap(~ sex)

Alternatively you could plot by both of them, but use the line type (solid or dashed) to distinguish sex:

ggplot(mydata, aes(tb, ts, col=pop, lty=sex)) + geom_point() +
             geom_smooth(method="lm", se=FALSE)

Upvotes: 3

Related Questions