【问题标题】:dplyr + ggplot2: Plotting not working via pipingdplyr + ggplot2:绘图无法通过管道工作
【发布时间】:2015-11-07 16:26:58
【问题描述】:

我想绘制我的数据框的一个子集。我正在使用 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

感谢您的帮助!

【问题讨论】:

  • 也许问题是在第二个ggplot 中你必须使用. 而不是data
  • 这很快。谢谢!
  • 请不要将答案发布为对您问题的编辑,将其发布为答案(您可能需要等待一段时间)...

标签: r ggplot2 dplyr


【解决方案1】:

我通常这样做,这也省去了.的需要:

library(dplyr)
library(ggplot2)

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

【讨论】:

    【解决方案2】:

    版本 2 的解决方案:点 .而不是数据:

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

    【讨论】:

    • 从技术上讲,您也可以省略 .,例如 iris %&gt;% filter(Species == "setosa") %&gt;% ggplot(aes(x = Sepal.Width, y = Sepal.Length)) + geom_point(),但使用明确的 . 可能更容易阅读
    【解决方案3】:

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

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

    希望它对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-06
      • 2015-05-21
      • 2013-04-06
      • 2011-05-04
      • 1970-01-01
      • 2012-06-26
      • 2020-01-10
      • 2023-04-07
      相关资源
      最近更新 更多