Те же переменные из 2 отдельных данных.фреймы, расположенные рядом в ggplot2

#r #ggplot2 #plot #tidyverse

#r #ggplot2 #график #tidyverse

Вопрос:

Я хочу отобразить одинаковые имена переменных ( ses amp; math ) из 2 отдельных data.frames ( dat1 amp; dat2 ), но рядом, чтобы я мог визуально сравнить их.

Я пробовал следующее, но он помещает оба фрейма данных друг на друга.

Есть ли внутри функция ggplot2 для построения ses графиков по сравнению math с dat1 исходными и одинаковыми рядом друг с dat2 другом и размещенными на одних и тех же шкалах осей?

 library(ggplot2)

dat1 <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')
dat2 <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/sm.csv')

ggplot(dat1, aes(x = ses, y = math, colour = factor(sector)))  
  geom_point()   
  geom_point(data = dat2, aes(x = ses, y = math, colour = factor(sector)))
  

Ответ №1:

Вы можете попробовать фасетирование, объединив два набора данных :

 library(dplyr)
library(ggplot2)

list(dat1 = dat1 %>% 
              select(sector,ses, math) %>%
              mutate(sector = as.character(sector)) , 
    dat2 = dat2 %>% select(sector,ses, math)) %>%
  bind_rows(.id = 'name') %>%
  ggplot()   
  aes(x = ses, y = math, colour = factor(sector))  
  geom_point()  
  facet_wrap(.~name)
  

введите описание изображения здесь


Другой вариант — создать список графиков и упорядочить их с помощью grid.arrange :

 list_plots <- lapply(list(dat1, dat2), function(df) {
  ggplot(df, aes(x = ses, y = math, colour = factor(sector)))    geom_point()
})

do.call(gridExtra::grid.arrange, c(list_plots, ncol = 2))