1

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:

  • title = "Hyperplanes"
  • red solid line = "1 + 3*x1 - x2 = 0"
  • green solid line = "-2 + x1 + 2*x2 = 0"
  • position = bottom of the plot

Can you help me?

neilfws
  • 32,751
  • 5
  • 50
  • 63
Sandy Vo
  • 11
  • 2

1 Answers1

2

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

rawr
  • 20,481
  • 4
  • 44
  • 78
  • Great Job. Wasn't aware that this works. My approach to tackle similar problems always included extracting the legend via cowplot as an intermediate step then glueing only the legend via pw. :D But yours is much easier. – stefan Aug 09 '22 at 06:04