Создание нескольких ggplots с помощью dplyr - PullRequest
0 голосов
/ 21 сентября 2018

После создания матрицы графика с использованием GGally::ggpairs() я хотел бы сохранить отдельные точечные диаграммы для последующего использования.

Вот мой текущий код:

# load necessary package
library(GGally) # loads `ggplot2` 
library(magrittr) # allows for the use of `%>%`

# create a matrix of plots
mtcars %>%
  na.omit() %>%
  ggpairs(columns = 1:7)

# how do I automate this process?
P1 <- ggplot(aes(x = disp, y = hp)) + 
        geom_point()
P2 <- ggplot(aes(x = drat, y = hp)) + 
        geom_point()
P3 <- ggplot(aes(x = hp, y = qsec)) + 
        geom_point()

Я получаю сообщение об ошибке, в котором говорится, что данные должны быть кадром данных.Я попытался указать данные из канала na.omit(), используя ., но получил тот же результат.

Любой совет приветствуется!

1 Ответ

0 голосов
/ 21 сентября 2018

Обзор

Я собрал все отдельные вызовы ggplot(...) в одну пользовательскую функцию: ScatterPlot().

Затем я создал еще одну пользовательскую функцию ManyScatterPlots() - которая использует purrr::map() - которая сохраняет отдельный график рассеяния для каждого конкретного столбца в df на оси x и в каждом столбцена оси Y в списке.Этот процесс повторяется для каждого столбца в df.

Результат от ManyScatterPlots() представляет собой список списков, где каждый отдельный список содержит много диаграмм разброса.Я пометил как список списков, так и отдельные участки, чтобы потом было легче найти то, что вы ищете.

Crappy screenshot

# load necessary package -----
library(tidyverse)

# create a function that makes one scatter plot
ScatterPlot <- function(df, x, y) {
  # Input: 
  #     df: a data frame
  #     x: a column from df in the form of a character vector
  #     y: a column from df in the form of a character vector
  #
  # Output:
  #     a ggplot2 plot
  require(ggplot2)

  ggplot(data = df, aes(x = get(x), y = get(y))) +
    geom_point() +
    xlab(x) +
    ylab(y) +
    labs(title = paste0(y, " as explained by ", x))
}

# create a function that plots one ScatterPlot() for every possible column combination  -------
ManyScatterPlots <- function(df) {
  # Input: 
  #     df: a data frame
  #
  # Output:
  #     a list of ggplot2 plots from ScatterPlot()
  require(magrittr)
  require(purrr)

  # for each column in df
  # create an individual scatter plot for that column on the x-axis
  # and every column on the y-axis
  colnames(df) %>%
    map(.f = function(i) 
      map(.x = colnames(df), .f = function(j)
        ScatterPlot(df = df, x = i, y = j)) %>%
        # to help identify the individual plots for that particular column
        # label the plots inside the list
        purrr::set_names(nm = paste0(colnames(df)
                                     , " as explained by "
                                     , i))) %>%
    # to help identify the list of plots for each particular column
    # label the plots inside the list
    purrr::set_names(nm = colnames(df))
}

# use ManyScatterPlots() -----
many.plots <- ManyScatterPlots(df = mtcars)

# view results ---
names(many.plots)           # a list of lists
map(.x = many.plots, names) # a list of individual scatter plots
many.plots$disp$`hp as explained by disp`
many.plots$drat$`hp as explained by drat`
many.plots$hp$`qsec as explained by hp`

# end of script #
...