Remove one regression line but not the other using geom_smooth in ggplot2

Hi there! I am attempting to remove one regression line that is not significant but leave the one that is, I have 2 groups of data that I used as fill (2 seasons, spring and summer) and I want to leave the regression line for spring but not for summer (see plot below). This is my code:

y.lab <- expression(bold("RAMP Score"))
x.lab <- expression(bold("Cortisol (ng/mL)"))
RAMPcortisol <- ggplot(data = cortisoldiffdata, mapping = aes(x = cortisoldiff, y = correctramp, fill = season, colour = season)) +
geom_point(size = 1.75, alpha = 3/4) +
geom_smooth(method='lm', formula = y~x, se=FALSE) +
labs(x = x.lab, y = y.lab, fill = "Season", colour = "Season") +
theme_classic() +
theme(axis.text = element_text(size = 11),
axis.title = element_text(size = 12)) +
scale_fill_manual(values = c("#08519c", "#0F7216"), labels = c("Spring", "Summer")) +
scale_colour_manual(values = c("#08306b", "#034E08"), labels = c("Spring", "Summer")) +
ylim(0,5)
RAMPcortisol

and this is the plot that it gives me:

I wasn't able to find anything just by searching. Any help would be greatly appreciated!

Hi, and welcome.

Could you post a reprex: FAQ: What's a reproducible example (`reprex`) and how do I do one?

Although the code is in your question, there's no data. You can reproduce it with

df. <- dput(cortisoldiffdata)

otherwise, folk will have to look for a similar dataset.

Also, it would be preferable to strip the reprex to the essential elements

RAMPcortisol <- ggplot(data = cortisoldiffdata, mapping = aes(x = cortisoldiff, y = correctramp, fill = season, colour = season)) +
geom_point(size = 1.75, alpha = 3/4) +
geom_smooth(method='lm' ...

I second @technochrat 's point. Minimal reprex would help.

Try removing "fill = season, colour = season" from the ggplot function for single regression line. If the season is a factor, it will fit two regression lines.

2 Likes

Or try taking fill/colour out of aes(). Llike this

ggplot(data = cortisoldiffdata, mapping = aes(x = cortisoldiff, y = correctramp), fill = season, colour = season)

1 Like

You'll want to subset inside geom_smooth, setting (it looks like) season=Spring. Something like:
geom_smooth(data=subset(cortisoldiffdata,season=Spring),

2 Likes

Thank you all so much! Someone sent me this link and it worked perfectly: https://stackoverflow.com/questions/15412413/add-regression-line-ggplot-for-only-certain-groups

Next time I will definitely post a reprex, sorry about that I just joined this site and didn't know what that was.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.