是否可以编写使用ggplot生成多个图形的函数?

时间:2019-09-19 17:03:46

标签: r function ggplot2 histogram

我正在尝试编写一个函数,该函数将使用ggplot生成多个直方图(每个因子水平一个)。

对于我正在使用的数据集,我使用facet_wrap创建了一个图矩阵,但是我的因子有15个级别,每个级别的计数对于每个bin都有很大差异,因此直方图不是很有用,因为我被迫以相同的比例查看每个直方图(例如,一个级别的最大计数为〜4,000,而另一个级别的最大计数为〜100)。

下面是我尝试使用iris数据集作为示例来完成的事情。

data(iris)
library(tidyverse)

histo_func = function(df){
  species_list = unique(df$Species) #create a vector of levels for Species
  for (i in seq_along(species_list)) {
    species_plot = ggplot(subset(df, df$Species==species_list[i]),
              aes(Sepal.Length)) +
              geom_histogram()
  }
}

species_hist = histo_func(df = iris)

 species_hist
NULL

运行该函数后,我调用species_hist并获得NULL。

该函数本身起作用-如果我逐步使用debugonce(),则可以调用species_plot并获取循环在那一点循环的i的直方图。

我想要(如果可能的话)是将直方图存储在species_hist中,并能够在调用species_hist时连续输出所有直方图。

首先感谢您的任何输入。

1 个答案:

答案 0 :(得分:0)

代码的问题“ species_plot”在循环的每次迭代中均被覆盖。您将需要使用以上注释中提到的print语句,或将对象存储在列表中。
同样,您也没有明确定义要从函数返回的变量。

histo_func = function(df){
  species_plot=list()
  species_list = unique(df$Species) #create a vector of levels for Species
  for (i in seq_along(species_list)) {
    species_plot[[i]] = ggplot(subset(df, df$Species==species_list[i]),
                          aes(Sepal.Length)) +
      geom_histogram()
  }
  names(species_plot) = species_list
  species_plot
}

species_hist = histo_func(df = iris)

species_hist

以上代码将每个图作为对象存储在列表中,然后使用种类名称命名列表元素,然后将整个结构返回给调用变量。