How to Add Legend to Geom_Smooth in Ggplot in R

How to add legend to geom_smooth in ggplot in R

Put the colour in aes() and add scale_colour_manual():

ggplot(data = temp, aes(x, y)) + geom_point() + 
geom_smooth(method = 'lm', formula = y ~ bs(x, df=5, intercept = T), aes(colour="A")) +
geom_smooth(method = 'lm', formula = y ~ ns(x, df=2, intercept = T), aes(colour="B")) +
scale_colour_manual(name="legend", values=c("blue", "red"))

Sample Image

Add a legend to geom_smooth that does not have an aes aesthetic call

Just add another aes mapping in the second geom_smooth() call:

p <- ggplot(mtcars, aes(disp, mpg)) +
geom_point(aes(color = factor(cyl)), show.legend = FALSE) +
geom_smooth(aes(color = factor(cyl)), se = FALSE, method = "lm") +
geom_smooth(se = FALSE, method = "lm", fullrange = TRUE,
aes(color = "all data")) +
scale_color_manual(values = c(scales::hue_pal()(3), "black"))
print(p)

plot

Add legend using geom_point and geom_smooth from different dataset

If you need to label the mean, might need to be a bit creative, because it's not so easy to add legend manually in ggplot.

I simulate something that looks like your data below.

dat1 = data.frame(
Hour = rep(1:24,each=10),
value = c(rnorm(60,0,1),rnorm(60,2,1),rnorm(60,1,1),rnorm(60,-1,1))
)
# classify this as raw data
dat1$Data = "Raw"
# calculate mean like you did
dat2 <- dat1 %>% group_by(Hour) %>% summarise(value=mean(value))
# classify this as mean
dat2$Data = "Mean"

# combine the data frames
plotdat <- rbind(dat1,dat2)
# add a dummy variable, we'll use it later
plotdat$line = "Loess-Smooth"

We make the basic dot plot first:

ggplot(plotdat, aes(x = Hour, y = value,col=Data,size=Data)) +
geom_point() +
scale_color_manual(values=c("blue","darkgray"))+
scale_size_manual(values=c(3,1),guide=FALSE)

Sample Image

Note with the size, we set guide to FALSE so it will not appear. Now we add the loess smooth, one way to introduce the legend is to introduce a linetype, and since there's only one group, you will have just one variable:

ggplot(plotdat, aes(x = Hour, y = value,col=Data,size=Data)) +
geom_point() +
scale_color_manual(values=c("blue","darkgray"))+
scale_size_manual(values=c(3,1),guide=FALSE)+
geom_smooth(data=subset(plotdat,Data="Raw"),
aes(linetype=line),size=1,alpha=0.3,
method = "loess", span = 0.2, color = "red", fill = "blue")

Sample Image

Changing the legends of plot using geom_smooth in ggplot2

Do you get the error if you run the code like this?

ggplot(mtcars, aes(x=mpg, y=disp, group=group)) +
geom_smooth(method=lm, se=FALSE,fullrange=TRUE, show.legend=TRUE,aes(linetype=group), colour="black")+
labs(linetype="Legend")+
scale_linetype_discrete(labels=c("Experiment", "Control"))

I get this plot:

Sample Image

Mixed fill color in ggplot2 legend using geom_smooth() in R

You can add the fill as an aesthetic mapping, ensuring you name it the same as the color mapping to get legends to merge:

library(ggplot2)

ggplot(data=iris, aes(x=Sepal.Width, y=Sepal.Length)) +
geom_point(aes(shape = "data")) +
geom_smooth(method=loess, aes(colour="Loess", fill="Loess")) +
geom_smooth(method=lm, aes(colour="LM", fill = "LM")) +
scale_fill_manual(values = c("yellow", "gray"), name = "model") +
scale_colour_manual(values = c("red", "blue"), name = "model") +
labs(shape = "")

Sample Image

How to add multiple geom_smooth lines to the legend (ggplot)?

Your data is in the wide format, or like a matrix. There's no easy way to add a custom legend in ggplot, so you need to transform your current data to a long format. I simulated 3 curves like what you have, and you can see if you call geom_line or geom_smooth with a variable ("name" in the example below) that separates your different values, it will work and produce a legend nicely.

library(dplyr)
library(tidyr)
library(ggplot2)
X = 1:50
#simulate data
Data = data.frame(
BA=X,
BAgp1 = log(X)+rnorm(length(X),0,0.3),
BAgp2 = log(X)+rnorm(length(X),0,0.3) + 0.5,
BAgp3 = log(X)+rnorm(length(X),0,0.3) + 1)

# convert this to long format, use BA as id
Data <- Data %>% pivot_longer(-BA)
#define colors
COLS = c("red","turquoise","orange")
names(COLS) = c("BAgp1","BAgp2","BAgp3")
###
ggplot(Data) +
geom_smooth(aes(BA,value,colour=name,fill=name)) +
# change name of legend here
scale_fill_manual(name="group",values=COLS)+
scale_color_manual(name="group",values=COLS)

Sample Image

ggplot2: Adding geom_smooth() destroys the point legend

I think it is because size=mean.unemploy is placed globally. If you put it in the aes of ggplot, it would affect whole geom. It means that the new geom_smooth would read the size argument, either.

Since the size is only needed for the geom_point, it is okay to put it in mapping of _point. You might only change that part.

library(tidyverse)
# your dataset
ggplot(econ3, aes(x=decade, y=mean.uempmed),guide=FALSE) + # remove size aesthetic
geom_point(aes(size=mean.unemploy), colour="blue", fill="lightblue", shape=21) + # size aesthetic in geom_point
scale_size_area(max_size = 15)+
geom_smooth(method=lm, se=FALSE, formula = y~x, aes(color="lm"))+
theme_gray()+
labs(title = "Unemployment Level per Decade",
subtitle = "(1967-2015)",
caption = "Data from the US economic time series.",
tag = "Figure 3",
x = "Mean of Median Duration of Unemployment (Weeks)",
y = "Decade")

Sample Image

If you modify the first two lines, the legend of the points would not be touched.

How to create a linetype legend in ggplot with different dataframes

Bring the line linetype inside aes() and use lab() to give title for the legend.

ggplot() + 
geom_smooth(data = mydf1, aes(x, predicted, linetype = "Group 1"), method = "lm", colour = "black") +
geom_smooth(data = mydf2, aes(x, predicted, linetype = "Group 2"), method = "lm", colour = "black") +
geom_smooth(data = mydf3, aes(x, predicted, linetype = "Group 3"), method = "lm", colour = "black") +
labs(linetype="Group") +
theme_classic()

Sample Image



Related Topics



Leave a reply



Submit