在刻面时抑制NA列

时间:2016-10-19 21:18:11

标签: r ggplot2

在我的情节中,分面由两列组成:

ggplot(peakDF, aes (Mass, Intensity)) + geom_line()+ facet_grid(file ~ fragment, scales = "free")
片段列中的

我有很多NA值,所以用这些NA生成一列图,如下所示:

enter image description here

问题是我不想要这个专栏,但我不能简单地过滤此列中的NA值,因为这会删除我真正需要的规范化(跨行)。有关如何保留整个数据集(用于规范化)但尚未绘制NA列的任何建议吗?

2 个答案:

答案 0 :(得分:2)

You can set up a fake data set to control the limits. This should be easy in your case--just calculate the max for Intensity by file. Or you can input custom limits like below

set.seed(1)
n <- 1e3
peakDF <- data.frame(Mass = rnorm(n, 500, 50),
                     Intensity = runif(n, 0, 10),
                     file = sample(letters[1:4], n, TRUE),
                     fragment = sample(letters[1:6], n, TRUE))
peakDF$fragment[1:(n/2)] <- NA

what you have now

ggplot(peakDF, aes (Mass, Intensity)) +
  geom_line()+
  facet_grid(file ~ fragment, scales = "free")

enter image description here

with na.omit and changing the upper limit for file=='a'

ggplot(na.omit(peakDF), aes (Mass, Intensity)) +
  geom_line()+
  facet_grid(file ~ fragment, scales = "free") +
  geom_blank(data = data.frame(Mass = Inf,
                               fragment = 'a',
                               file = 'a',
                               Intensity = 15))

enter image description here

You can add multiple controls at the same time. In your case you could just get the max value for the NAs by file and use that summary data frame

ggplot(na.omit(peakDF), aes (Mass, Intensity)) +
  geom_blank(data = data.frame(Mass = rep(Inf, 4),
                               fragment = rep('a', 4),
                               file = c('a', 'a', 'c', 'd'),
                               Intensity = c(15, -5, 50, -5))) +
  geom_line()+
  facet_grid(file ~ fragment, scales = "free")

enter image description here

This would also work for the x-axis or both the x- and y.

答案 1 :(得分:1)

如果没有您的数据,很难做到这一点,但一种选择是转换为gtable对象,然后修剪掉您不想要的额外列。

我的示例代码将使用内置于mtcars的R。

library(ggplot2)
library(gtable)
p<-ggplot(mtcars, aes(wt, hp)) + geom_point()+ facet_grid(cyl ~ carb, scales = "free")
gt<-ggplot_gtable(ggplot_build(p))

不修剪

grid.draw(gt)

enter image description here

使用修剪

gt2<-gt[,-14]
grid.draw(gt2)

enter image description here

你可以看到,通过修剪我们只是摘下了我们不想要的最后一列(第14列,其中有8个圆柱图)。要确定要修剪的列,您可以执行以下操作:

gtable_show_layout(gt)

使用此功能,您可以将绘图的特定方面与要删除的gtable中的列相匹配。 enter image description here