【问题标题】:Filter a piped df within ggplot在ggplot中过滤管道df
【发布时间】:2020-01-28 21:32:11
【问题描述】:

我正在使用 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)

现在用管道清理它(这里我们只是对它做一些随机的东西),然后绘图:

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()

所以我想一次只绘制一年(从“年”列),但我想以一种可以循环绘制每一年的方式来绘制,但保持颜色条缩放到完整的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()

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

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()

但这给了我这个错误:

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

最好的方法是什么?

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

    您可以不可见地绘制一层,然后使用data = . %&gt;% 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]))
    

    【讨论】:

      【解决方案2】:

      您可以使用scale_color_gradient 并设置您的规模限制:

      df %>%
          filter(var3 < 80 & 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()+
          scale_color_gradient(limits = c(min(df$var2),max(df$var2)))
      

      【讨论】:

      • 当然可以,但这将限制设置为管道前原始 df 的最小值/最大值。有没有办法在过滤后设置 df 的限制? (我更改了其中一个管道过滤器以使其更具相关性)
      • 在真实数据集中,颜色值是我在 dplyr 管道中创建的列,因此我希望能够将限制设置到该点。
      • 对这个误会深表歉意。我认为@Jon Spring 为您的问题提供了一个很好的解决方案,对吗?
      猜你喜欢
      • 1970-01-01
      • 2020-10-24
      • 2013-03-14
      • 1970-01-01
      • 2017-10-04
      • 2017-11-29
      • 1970-01-01
      • 2017-03-30
      相关资源
      最近更新 更多