绘制R中的lapply后的各个直方图

时间:2016-09-12 07:28:08

标签: r plot datatables histogram lapply

我在使用数据表上的lapply后绘制个人直方图时遇到问题。该指令绘制了所有直方图,但我需要单独访问它们。所有直方图对象都可以在列表中使用,但是当我访问(例如)最后一个直方图对象并尝试绘制它时,会出现错误。代码如下所示。

我使用mt cars数据集并从中形成一个表。

library(data.table)
mtcars$carname <- rownames(mtcars)
mtcars_dt <- data.table(mtcars)
histograms<- mtcars_dt[, lapply(.SD[, 1:10, with=F], hist), by=cyl]
# The above will plot all 30 data frames ie 10 for each value of cyl (3 of) 
# I now want to plot a single histogram, lets say the 10th one
b=histograms[[10]] # this is a histogram object
plot(b) # try to plot the object 
#
# Result is the error shown below:

# Error in if (freq && !equidist) warning("the AREAS in the plot are wrong -      
#- rather use 'freq = FALSE'") : 
#missing value where TRUE/FALSE needed
# In addition: Warning messages:
# 1: In min(x, na.rm = na.rm) :
# no non-missing arguments to min; returning Inf
# 2: In max(x, na.rm = na.rm) :
##no non-missing arguments to max; returning -Inf
#3: In mean.default(h) : argument is not numeric or logical: returning NA

之前我已经绘制了直方图对象,但是我注意到当我对这个对象执行str时,它在列表中的元素比简单的直方图要多得多。最后一个元素是一个attr元素,旁边有一个直方图。我不确定是否需要访问该元素或锄头才能访问它。

感谢任何帮助

由于 ģ

1 个答案:

答案 0 :(得分:0)

我不是data.table专家。但我会使用ggplot2进行绘图:

首先创建一个函数,每个cyl

绘制三个直方图
foo <- function(x){
 require(ggplot2)
 ggplot(mtcars, aes(x = x)) + geom_histogram() + facet_grid(. ~ cyl)
}

对列进行lapply功能,将列表保存在列表中

histograms <- lapply(mtcars, foo)

现在您可以通过

访问各个图表了
histograms[3]
# or
histograms$disp

enter image description here