SiH
SiH

Reputation: 1546

Plot lines with different slopes on each facet of ggplot

I have two facets in ggplot. I want to plot different lines in each facet.

Below is a sample code. Please help me to add lines with slope -1 and 1 in each facet using geom_abline() (code attached in bracket)

Thanks


library(tidyverse)

x <- runif(n = 100, 
           min = -1,
           max = 1)
y <- runif(n = 100, 
           min = -1,
           max = 1)
Male <- c(rep(x = 0, 50),
          rep(x = 1, 50))

# tibble 
tbl <- tibble(x, y, Male)

# plot
ggplot(data = tbl,
       aes(x = x,
           y = y)) + 
  geom_point() + 
  facet_grid(. ~ Male) + 
  theme_bw() + 
  theme(aspect.ratio = 1)

  # code to add line based on slope and intercept
  # geom_abline(intercept = 0, slope = -1) + 
  # geom_abline(intercept = 0, slope = 1)

Upvotes: 1

Views: 498

Answers (1)

MrFlick
MrFlick

Reputation: 206243

I'm guessing you are asking how to add a slope of -1 in the Male=0 facet and a slope of 1 in the Male = 1 facet. To do that, you need data for that layer that has a Male column that can be used for faceting. The easiest way to do that is pass a data.frame with values for mapping. For example

ggplot(data = tbl,
       aes(x = x,
           y = y)) + 
  geom_point() + 
  facet_grid(. ~ Male) + 
  geom_abline(aes(intercept=i, slope=s), 
    data=data.frame(Male=c(0,1), i=0, s=c(-1,1))) + 
  theme_bw() + 
  theme(aspect.ratio = 1)

enter image description here

Upvotes: 3

Related Questions