跳过facet_wrap中包含少于10个点的图-访问ggplot数据点

时间:2019-04-18 11:07:21

标签: r ggplot2

当情节包含少于10个数据点时,是否可以跳过geom_point中的facet_wrap个情节?

我正在使用这样的代码:

ggplot(data) + 
    geom_point(aes(x = Height, Y = Weight, shape = Gender, col = InstrumentUsed)) + 
    facet_wrap(ID ~ Institute, drop = T)

我有两个问题

  1. 如果xy中的一个充满了NA值,则该图仍在facet中显示为空白图。我不希望打印这些图。但这似乎只是因为提供的一列是非NA /非空,ggplot仍然绘制了这样一个空图!
  2. 如果单个图中的数据点少于10个,我根本不希望打印该图。

问题

是否可以访问ggplot对象的基础结构并轻松过滤包含少于10个数据点的对象?

示例数据

这可以通过dget加载: https://drive.google.com/open?id=1chulcK5yinAOE6R11UKyi6IFekdNvyaa

例如

data <- dget("https://drive.google.com/uc?export=download&id=1chulcK5yinAOE6R11UKyi6IFekdNvyaa")

1 个答案:

答案 0 :(得分:1)

我相信在这种情况下,一个非常简单的解决方案就是删除任何包含NA的行。

library(tidyverse)
data = dget("data.txt") %>%
  as_tibble()

data = data %>%
  filter(complete.cases(.))

#All remaining groups have more than 10 data points:
> data %>% 
+   group_by(ID, Institute) %>%
+   group_size()
[1]  916 1674  607  831  179 1386   55  968 4002

#Edit: If you want to exclude groups with a certain number of datapoints
#      (55 in this case to exclude at least one group) you could do 
#      something like this: 

data_cleaned = data %>%
  group_by(ID, Institute) %>%
  mutate(n = n()) %>%
  filter(n >55)

在不删除小组的情况下绘制数据:

ggplot(data) + 
  geom_point(aes(x = Height, y = Weight, shape = Gender, col = InstrumentUsed)) + 
  facet_wrap(ID ~ Institute, drop = T)

enter image description here

在删除小组的情况下绘制数据:

ggplot(data_cleaned) + 
  geom_point(aes(x = Height, y = Weight, shape = Gender, col = InstrumentUsed)) + 
  facet_wrap(ID ~ Institute, drop = T)

enter image description here