gpt4 book ai didi

r - 使用 dplyr 创建多个 ggplot

转载 作者:行者123 更新时间:2023-12-05 04:04:35 25 4
gpt4 key购买 nike

使用 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() 管道的数据,但我收到了相同的结果。

感谢任何建议!

最佳答案

概览

我将所有单独的 ggplot(...) 调用压缩为一个自定义函数:ScatterPlot()

然后我创建了另一个自定义函数 ManyScatterPlots() - 它使用 purrr::map() - 将 df 中每个特定列的单个散点图存储在 x 轴上,并将每个列存储在列表中的 y 轴上。对 df 中的每一列重复此过程。

ManyScatterPlots() 的结果是一个列表列表,其中每个单独的列表包含许多散点图。我已经标记了列表列表和各个地 block ,以便以后更容易找到您要查找的内容。

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 #

关于r - 使用 dplyr 创建多个 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52434628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com