在 ggplot 中过滤管道 df

Jak*_*e L 4 r ggplot2 dplyr

我正在使用 dplyr 管道来清理我的 df,然后直接输入到 ggplot 中。但是,我只想一次只绘制一组,因此我需要过滤到该组。问题是,我希望比例保持不变,就好像所有群体都存在一样。是否可以在 ggplot() 命令中进一步过滤管道 df?例如下面。

# create df
set.seed(1)
df <- data.frame(matrix(nrow=100,ncol=5)) 
colnames(df) <- c("year","group","var1","var2","var3") 
df$year <- rep(1:4,each=25)
df$group <- rep(c("a","b","c","d","e"),times=20)
df$var1 <- runif(100,min=0,max=30)
df$var2 <- sample(1:500,100,replace=T) 
df$var2[1:25] <- sample(1:100,25,replace = T)
df$var3 <- runif(100,min=0,max=100)
Run Code Online (Sandbox Code Playgroud)

现在通过管道来清理它(这里我们只是对其进行一些随机的操作),然后绘制:

df %>%
  filter(var3 < 80) %>%   # random thing 1 - filter some stuff
  filter(var2 < 400) %>%   # random thing 2 - filter more
  mutate(var2 = as.numeric(var2)) %>%  # random thing 3 - mutate a column
  ggplot(aes(x=group,y=var1,color=var2)) + 
  geom_point()
Run Code Online (Sandbox Code Playgroud)

所以我只想一次绘制一年(从“年”列),但我想以一种可以循环绘制每年的方式来实现,但保持颜色条缩放到完整的 df 值。

到目前为止,这是我尝试过的:

dlist <- c(1:4)   #list of years
i <- 2    #current year

df %>%
  filter(var3 < 80) %>%
  filter(var2 != 56) %>%
  mutate(var2 = as.numeric(var2)) %>%
  filter(year %in% dlist[i]) %>%   # so I can filter for year here, but that makes the colorbar in the ggplot scale for this subset individually, which is no good. 
  ggplot(aes(x=group,y=var1,color=var2)) + 
  geom_point()
Run Code Online (Sandbox Code Playgroud)

我认为应该有一种方法可以在括号内使用.and ,以便比例保持不变......但我不太明白。%>%ggplot

dlist <- c(1:4)   #list of years
i <- 2    #current year

df %>%
  filter(var3 < 80) %>%
  filter(var2 != 56) %>%
  mutate(var2 = as.numeric(var2)) %>%
  ggplot(data = .%>%filter(year %in% dlist[i]), aes(x=group,y=var1,color=var2)) + 
  geom_point()
Run Code Online (Sandbox Code Playgroud)

但这给了我这个错误:

Error: You're passing a function as global data.
Have you misspelled the `data` argument in `ggplot()`
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

Jon*_*ing 11

您可以不可见地绘制一层,然后使用以下方法绘制过滤层data = . %>% filter(...

df %>%
  filter(var3 < 80) %>%
  filter(var2 != 56) %>%
  mutate(var2 = as.numeric(var2)) %>%
  ggplot(aes(x=group,y=var1,color=var2)) + 
  geom_point(alpha = 0) +
  geom_point(data = . %>% filter(year %in% dlist[i]))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述