Cauder
Cauder

Reputation: 2597

How to split ggplot chart by the x axis value?

I'd like to create a series of ggplot charts with different values for x.

This is what I've tried

df %>% 
  ggplot(aes(x = factor_var, y = response_var)) +
    geom_point() +
    stat_smooth() +
    facet_wrap(~factor_var)

Unfortunately this places the factor_var as the x axis value while what I really want is this

df %>% 
  filter(factor_var == 1) %>%
  ggplot(aes(x = independent_var y = response_var)) +
    geom_point() +
    stat_smooth()

And then that same chart for factor_var == 2 and then 3 and so on. I'd like them to show up in the same plot.

Upvotes: 0

Views: 533

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 173813

Difficult to tell without a reprex, but it sounds like your data is something like this:

library(ggplot2)
library(dplyr)

set.seed(69)

df <- data.frame(factor_var = factor(rep(1:6, 100)),
           independent_var = rnorm(600),
           response_var = rnorm(600))

And your first plot is wrong because it looks like this:

df %>% 
  ggplot(aes(x = factor_var, y = response_var)) +
  geom_point() +
  stat_smooth() +
  facet_wrap(~factor_var)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

You would be happier with something like this:

df %>% 
  filter(factor_var == 1) %>%
  ggplot(aes(x = independent_var, y = response_var)) +
  geom_point() +
  stat_smooth()
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

But you want a separate version for each of the factor variables, and you want them all on the same page. In that case, you put the independent variable on the x axis, the dependent variable on the y axis, and facet by the factor variable:

df %>% 
  ggplot(aes(x = independent_var, y = response_var)) +
  geom_point() +
  stat_smooth() +
  facet_wrap(~factor_var)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2020-07-14 by the reprex package (v0.3.0)

Upvotes: 1

akrun
akrun

Reputation: 887118

We can replace the x with the 'independent_var' (using a reproducible example, it can be 'gear' from mtcars, and the factor_var as 'cyl')

library(dplyr)
library(ggplot2)
mtcars %>%
    ggplot(aes(x = gear, y = mpg, color = cyl)) + 
        geom_point() + 
        stat_smooth() + 
        facet_wrap(~ cyl)

Or as we commented earlier, just use the x as independent_var

df %>% 
   ggplot(aes(x = independent_var, y = response_var)) +
     geom_point() +
     stat_smooth() +
     facet_wrap(~factor_var)

Upvotes: 1

Related Questions