ggplot facet_wrap读取所有输入数据为NaN(带循环过滤器)

时间:2018-11-07 11:00:58

标签: r ggplot2 facet

我正在尝试从根据for循环过滤的数据集中生成一系列山脊线图。

# create list object to hold charts

print_list=list()

# loop through dataset and create charts based on facility type

for (i in data$fac_type) {

  data_filter <- filter(data, fac_type == i)

  plot <- ggplot(data=data_filter,aes(x=average,y=category, fill=category)) +
          scale_fill_manual(values= cols) +
          geom_density_ridges(
           rel_min_height=0.01,scale=0.9,
           jittered_points = TRUE,
           position=position_points_jitter(width=0.05, height=0),point_shape="|",point_size=2,point_alpha=0.7, alpha=0.7) +
          theme_ridges() +
          theme(legend.position="none",axis.text.y = element_text(angle=45, hjust=1)) +
          stat_density_ridges(quantile_lines = TRUE,alpha=0.7,scale=0.9,quantiles=2) +
          scale_x_continuous(limits=c(0,1),labels = scales::percent) +
          facet_wrap(~season)

  print_list[[i]] = plot

}

# print the charts from the list

for (i in data$fac_type) {

    data_filter <- filter(data, fac_type == i)

    filename=paste("./Charts/National - ",data_filter$fac_type,".jpeg",sep="")
        jpeg(filename,width=9,height=7,units="in",bg="white",quality=1,res=300,type=c("quartz"))

    print(print_list[[i]])

    dev.off()
}

当我在没有facet_wrap的情况下运行上述代码时,我得到了愉快的数据处理消息"Picking joint bandwidth of 0.0182"和非常好的图表

工作面未过滤的图表:
Working unfaceted, filtered chart

但是实施facet_wrap会产生空数据集"Picking joint bandwidth of NaN"和相应的空白构面。

空的多面图表:
Empty filtered, faceted chart

奇怪的是,如果我使用未过滤的数据,则刻面效果很好。

工作面未过滤的图表:
Working faceted unfiltered chart

如果我将print(data_filter)插入原始的for循环中,它将显示正确过滤的数据集,如下所示

已过滤的数据段:
Filtered data snippet

因此,我得出结论,问题在于facet_wrap在重新打包图表时以某种方式处理数据。大量使用Google搜索和堆栈溢出搜索并没有提供任何线索来解释为什么会这样。我怀疑这与ggplot的内部运作有关,我是新手。

还是建议另一种更优雅的方式来做到这一点?我需要对几组数据重复此操作,所以我需要一个可扩展的解决方案。

最后一点,我知道使用lapply和自定义函数来完成上述操作可能更优雅-并欢迎提出建议。由于时间紧迫,我无法自己弄清楚。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则问题可能是您正在使用作为因素的变量进行筛选和/或构面。当您过滤因子时,因子水平保持不变,这可能会导致构面出现问题。如果确实是这些变量,请尝试在过滤后添加一个droplevels()调用,看看它是否有效。

相关问题