如何绘制具有不同类别变量的大量密度图

时间:2019-04-11 02:46:48

标签: r ggplot2 density-plot

我有一个数据集,其中有一个数字变量和许多类别变量。我想制作一个密度图网格,每个密度图显示不同类别变量的数字变量的分布,填充对应于每个类别变量的子组。例如:

library(tidyverse)
library(nycflights13)

dat <- flights %>%
  select(carrier, origin, distance) %>%
  mutate(origin = origin %>% as.factor,
         carrier = carrier %>% as.factor)

plot_1 <- dat %>%
  ggplot(aes(x = distance, fill = carrier)) +
  geom_density()

plot_1

plot_2 <- dat %>%
  ggplot(aes(x = distance, fill = origin)) +
  geom_density()

plot_2

我想找到一种方法来快速绘制这两个图。现在,我知道如何执行此操作的唯一方法是分别创建每个图,然后使用grid_arrange将它们放在一起。但是,我的真实数据集具有大约15个分类变量,因此这将非常耗时!

是否有更快,更轻松的方法来做到这一点?我认为最难的部分是每个剧情都有自己的传说,所以我不确定如何解决这个绊脚石。

2 个答案:

答案 0 :(得分:1)

此解决方案在列表中列出了所有图解。在这里,我们制作了一个函数,该函数接受要绘制的变量,然后将lapply与要绘制的所有变量的向量一起使用。

fill_variables <- vars(carrier, origin)

func_plot <- function(fill_variable) {
  dat %>%
  ggplot(aes(x = distance, fill = !!fill_variable)) +
  geom_density()
}

plotlist <- lapply(fill_variables, func_plot)

如果您不了解!!的含义,建议您观看this 5 minute video that introduces the key concepts of tidy evaluation。当您要创建此类包装函数以编程方式进行操作时,便要使用此功能。我希望这会有所帮助!


编辑:如果您要填充字符串数组而不是四舍五入,则可以将!!fill_variable的{​​{1}}更改为:

!!sym(fill_variable)

答案 1 :(得分:0)

替代解决方案

@djc在评论中写道,I'm having trouble passing the column names into 'fill_variables'. Right now I am extracting column names using the following code...

您可以将类别和数字变量分开;例如; cat_vars <- flights[, sapply(flights, is.character)]用于分类变量,cat_vars <- flights[, sapply(flights, !is.character)]用于连续变量,然后将这些向量传递到mgiormenti给定的包装函数中

完整代码如下;

library(tidyverse)
library(nycflights13)

cat_vars <- flights[, sapply(flights, is.character)]
cont_vars<- flights[, !sapply(flights, is.character)]
dat <- flights %>%
  select(carrier, origin, distance) %>%
  mutate(origin = origin %>% as.factor,
         carrier = carrier %>% as.factor)

func_plot_cat <- function(cat_vars) {
  dat %>%
    ggplot(aes(x = distance, fill = !!cat_vars)) +
    geom_density()
}

func_plot_cont <- function(cont_vars) {
  dat %>%
    ggplot(aes(x = distance, fill = !!cont_vars)) +
    geom_point()
}

plotlist_cat_vars <- lapply(cat_vars, func_plot_cat)
plotlist_cont_vars<- lapply(cont_vars, func_plot_cont)
print(plotlist_cat_vars)
print(plotlist_cont_vars)