繁体   English   中英

是否可以编写一个 function 将使用 ggplot 生成多个图形?

[英]Is it possible to write a function that will generate multiple graphs using ggplot?

我正在尝试编写一个 function ,它将使用 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

运行 function 后,我调用species_hist并得到 NULL。

function 本身可以工作 - 如果我逐步使用debugonce()i可以调用species_plot并获取循环在该点循环通过的直方图。

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

提前感谢您的任何意见。

您的代码存在问题,每次循环迭代都会覆盖“species_plot”。 您将需要使用上述注释中提到的打印语句或将 object 存储在列表中。
此外,您没有明确定义要从 function 返回的变量。

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

上述代码将每个 plot 作为 object 存储在一个列表中,然后用物种名称命名列表元素,然后将整个结构返回给调用变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM