Sandy Vo
Sandy Vo

Reputation: 11

How to add legend manually without overwriting the others legends in ggplot2

First, below is my code

library(ggplot2)

x1 <- rnorm(200)
x2 <- rnorm(200,2,1) 

y <- ifelse(1 + 3*x1 - x2 > 0, "1 + 3*x1 - x2 > 0", "1 + 3*x1 - x2 < 0")
z <- ifelse(-2 + x1 + 2*x2 > 0, "-2 + x1 + 2*x2 > 0", "-2 + x1 + 2*x2 < 0")
dat <- data.frame(x1,x2,y,z)
ggplot(data = dat) + geom_point(aes(x1,x2, col = y, shape = z)) + 
geom_abline(intercept = 1, slope = 3, color="red", size=1.5) +  
geom_abline(intercept = 1, slope = -0.5, col = "green", size = 1.5)

enter image description here

I want to add another legend with:

Can you help me?

Upvotes: 1

Views: 194

Answers (1)

rawr
rawr

Reputation: 20811

Well I don't use ggplot, so there could actually be an easier way to do this, see this similar question with a bit of a hacky answer (although it is an old question) like the one below.

library('ggplot2')
set.seed(1)
x1 <- rnorm(200)
x2 <- rnorm(200,2,1) 

y <- ifelse(1 + 3*x1 - x2 > 0, "1 + 3*x1 - x2 > 0", "1 + 3*x1 - x2 < 0")
z <- ifelse(-2 + x1 + 2*x2 > 0, "-2 + x1 + 2*x2 > 0", "-2 + x1 + 2*x2 < 0")
dat <- data.frame(x1,x2,y,z)

p1 <- ggplot(data = dat) + geom_point(aes(x1,x2, col = y, shape = z)) + 
  geom_abline(intercept = 1, slope = 3, color="red", size=1.5) +  
  geom_abline(intercept = 1, slope = -0.5, col = "green", size = 1.5)
p1

dd <- data.frame(
  x1 = NA_real_, x2 = NA_real_,
  label = c('-2 + x1 + 2*x2 = 0', '1 + 3*x1 - x2 = 0')
)

p2 <- ggplot(dd, aes(x1, x2, color = label)) +
  geom_line() +
  labs(x = '', y = '', color = 'Hyperplanes') +
  scale_color_manual(values = c('green', 'red')) +
  theme(legend.position = c(0.5, 0), legend.direction   = 'horizontal',
        legend.background = element_rect(fill = 'transparent'))

library('patchwork')
p1 + p2 + plot_layout(heights = c(1, 0))

enter image description here

Upvotes: 2

Related Questions