nouse
nouse

Reputation: 3461

Adding selfmade factor levels to ggplot legends

I have data of the following type:

df <- data.frame(A=runif(100), 
                 B=rep(seq(1,50), each=2), 
                 C=factor(c(rep(c("X1", "X2"), 50))))

I then proceed to scatterplot A vs B and add a stat_smooth layer according to C.

p1 <- ggplot(df, aes(B,A)) +
  geom_point(aes(col=C)) +
  stat_smooth(aes(col=C))

I however want to show the relation between B and A disregarding the grouping factor C.

p1 + stat_smooth(col="black")

I would like to add this new, selfmade factor (X1+X2) to the legend. Is there a way to achieve this?

Upvotes: 1

Views: 40

Answers (1)

Wietze314
Wietze314

Reputation: 6020

You can try:

ggplot(df, aes(B,A)) +
  geom_point(aes(col=C)) +
  stat_smooth(aes(col=C)) +

  scale_colour_manual(name="Line Color",
                      values=c(X1="red", X2="blue", "X1-X2"="black"),
                      limits = c("X1","X2","X1-X2")) +
  stat_smooth(col = "black")

Upvotes: 1

Related Questions