chippycentra
chippycentra

Reputation: 3432

How to respect ratio size when merging ggplot2 figures

I'm looking for help in order to merge two plots and respect their respective scale size.

Here is a reproductible example:

    data1<- subset(mtcars, cyl = 4)
    data1$mpg <- data1$mp*5.6
    data2<- subset(mtcars, cyl = 8)
    
    p1 <- ggplot(data1, aes(wt, mpg, colour = cyl)) + geom_point() 
    p2 <- ggplot(data2, aes(wt, mpg, colour = cyl)) + geom_point()
    
    grid.arrange(p1, p2, ncol = 2)

enter image description here

But what I'm looking for is to merge the two plots and respect the scale size and get something like :

enter image description here

It would be nice to not use a package which need to define the ratio since it's difficult to known how much I should reduce the second plot compared to the first one... And event more difficult when we have more than 2 plots.

Upvotes: 1

Views: 53

Answers (1)

bird
bird

Reputation: 3326

I think what you are trying to achieve is something like this:

library(tidyverse)

mtcars %>% 
        filter(cyl %in% c(4, 8)) %>%
        mutate(mpg = ifelse(cyl == 4, mpg * 5.6, mpg)) %>% 
        ggplot(aes(x = wt, y = mpg, col = as.factor(cyl))) +
        geom_point(show.legend = FALSE) +
        facet_wrap(~ cyl)

enter image description here

NOTE: I see some bugs in your original code. For example, if you want to use subset() to subset your data, you have to change your code from:

data1 <- subset(mtcars, cyl = 4)

to:

data1 <- subset(mtcars, cyl == 4)

subset(mtcars, cyl = 4) does not do anything.

Upvotes: 1

Related Questions