dplyr + ggplot2:通过管道绘图无法工作

11

我想绘制数据框的一个子集。我正在使用dplyr和ggplot2。我的代码只在版本1中有效,而在通过管道传输的版本2中无效。有什么区别吗?

版本1(绘图有效):

data <- dataset %>% filter(type=="type1")
ggplot(data, aes(x=year, y=variable)) + geom_line()

版本 2,带有管道功能(绘图不起作用):

data %>% filter(type=="type1") %>% ggplot(data, aes(x=year, y=variable)) + geom_line()

错误:

Error in ggplot.data.frame(., data, aes(x = year,  : 
Mapping should be created with aes or aes_string

谢谢你的帮助!


6
也许问题在于第二个ggplot中你需要使用 . 而不是 data - SabDeM
这很快。谢谢! - kabr
2
请不要将答案作为问题的编辑发布,而是将其作为答案发布(您可能需要等待一段时间)... - Ben Bolker
3个回答

26

版本2的解决方案:使用一个点"."代替"data":

data %>% 
    filter(type=="type1") %>% 
    ggplot(., aes(x=year, y=variable)) + 
    geom_line()

12
从技术上讲,你也可以省略 .,比如这样写:iris %>% filter(Species == "setosa") %>% ggplot(aes(x = Sepal.Width, y = Sepal.Length)) + geom_point(),但是加上明确的 . 可能更容易阅读。 - talat

9
我通常这样做,这也省去了使用.的需要:
library(dplyr)
library(ggplot2)

mtcars %>% 
  filter(cyl == 4) %>%
  ggplot +
  aes(
    x = disp,
    y = mpg
  ) + 
  geom_point()

0

在使用管道符时,如果您重新输入了数据名称,就像我下面用粗体显示的那样,函数会混淆参数的顺序。

data %>% filter(type=="type1") %>% ggplot(***data***, aes(x=year, y=variable)) + geom_line()

希望这对您有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接