'Can you facet grid using cols as the x variable in the plot?

Using the Auto MPG data set as an example, I'd like to create plots showing the relationship between hwy milage ~ year, ~ displacement, ~ cyl. Can you do this using a facet grid where the rows are manufacturer and the cols = c(year, displacement, and cyl)?

I've only been able to do this in three individual plots so far and would like to combine into one plot.

ggplot(mpg, aes(year, hwy)) + 
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))

ggplot(mpg, aes(displ, hwy)) + 
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))

ggplot(mpg, aes(cyl, hwy)) + 
 geom_smooth(method = "lm", se = FALSE)+
 facet_grid(rows = vars(manufacturer))


Solution 1:[1]

In ggplot2, you can only facet on a single variable. The solution is to pivot your data into long form so that the variables you want to facet on are contained in a single variable. Here we take year, displ, and cyl and convert them into a name column (which we facet on) and a value column which we use for the X-axis value.

Note that we need to set the free scales at least on the X axis, since year the scales are so different between the different variables

mpg %>%
    pivot_longer(c(year, displ, cyl)) %>%
    ggplot(aes(value, hwy)) + 
    geom_smooth(method = "lm", se = FALSE)+
    facet_grid(rows = vars(manufacturer), cols=vars(name), scales = 'free')

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 divibisan