Add line in GGplot2

I want to keep my site names as different colors and keep my legend. I want to add only 1 line though, instead of each Site having a line of best fit. How do I do this?

Hi there,

A reprex or even just a copy/paste of your code would be easier to work off of, for future reference.

In any case, I think the code below is roughly what you're looking for with particular regards to the inherit.aes argument in geom_smooth in addition to the other arguments you might specify about the method, standard error, etc.

ggplot(your_data, aes(var1, var2, var3 ...)) +
geom_point() +
geom_smooth(data=your_data, aes(var1, var2), inherit.aes=F, ...)

The details: geom_*() functions automatically inherit aesthetics defined in ggplot(data, aes()). This is generally the preferred approach to using ggplot(), but you can write out aesthetics individually in each geom_*() function or use inherit.aes=F to circumvent this standard approach.

I think pcall gave you excellent advice.
Here is an example in action


RShiner <- iris %>% 
         Eye.Size = Sepal.Width,
         Site.Name = Species)

Plot.BL.EyeSize.RShiner<-ggplot(data=RShiner,aes(x=Body.Length, y=Eye.Size, color=Site.Name))+
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,
              aes(x=Body.Length, y=Eye.Size),
  labs(y = "Eye Diameter") +
  labs(x = "Body Length") +
  theme_bw(base_size = 14) +
  theme(panel.grid.major=element_blank(),panel.grid.minor=element_blank(),panel.border = element_blank()) +
  theme(axis.text.x = element_text(vjust = 0.5))+
  theme(axis.line = element_line(size = 1 ,color = 'black'))+
  theme(axis.title.x = element_text(hjust=0.6, vjust=-0.5, size= 16)) +
  theme(axis.title.y = element_text(hjust=0.5, vjust=0.5, size= 16))


I don't know what your data looks like without a reprex.

Here is a minimal demonstration of the code I mentioned previously using the iris dataset.

ggplot(iris, aes(x=Sepal.Length,y=Petal.Length,color=Species)) +
  geom_smooth(method="lm", se=FALSE, fullrange=FALSE) +
  geom_smooth(data=iris, aes(x=Sepal.Length, y=Petal.Length), 
              inherit.aes = F, method="lm", se=FALSE, fullrange=FALSE)

The first geom_smooth() call creates the lines by species. The second geom_smooth() call, as a result of the inherit.aes=F argument, creates a single line. Note that you have to define data and your aes() arguments again.

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.