Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr + ggplot2: Plotting not working via piping

Tags:

r

dplyr

ggplot2

I want to plot a subset of my dataframe. I am working with dplyr and ggplot2. My code only works with version 1, not version 2 via piping. What's the difference?

Version 1 (plotting is working):

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

Version 2 with piping (plotting is not working):

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

Error:

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

Thanks for your help!

like image 1000
kabr Avatar asked Aug 14 '15 12:08

kabr


People also ask

What does %>% do in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

Can you pipe into ggplot?

The %>% operator can also be used to pipe the dplyr output into ggplot. This creates a unified exploratory data analysis (EDA) pipeline that is easily customizable. This method is faster than doing the aggregations internally in ggplot and has the added benefit of avoiding unnecessary intermediate variables.

Does ggplot only work with data frames?

ggplot only works with data frames, so we need to convert this matrix into data frame form, with one measurement in each row. We can convert to this “long” form with the melt function in the library reshape2 . Notice how ggplot is able to use either numerical or categorical (factor) data as x and y coordinates.

What does GG stand for in ggplot?

ggplot2 [library(ggplot2)] ) is a plotting library for R developed by Hadley Wickham, based on Leland Wilkinson's landmark book The Grammar of Graphics ["gg" stands for Grammar of Graphics].


2 Answers

Solution for version 2: a dot . instead of data:

data %>% 
    filter(type=="type1") %>% 
    ggplot(., aes(x=year, y=variable)) + 
    geom_line()
like image 188
kabr Avatar answered Oct 09 '22 22:10

kabr


I usually do this, which also dispenses with the need for the .:

library(dplyr)
library(ggplot2)

mtcars %>% 
  filter(cyl == 4) %>%
  ggplot +
  aes(
    x = disp,
    y = mpg
  ) + 
  geom_point()
like image 29
Matt Upson Avatar answered Oct 09 '22 20:10

Matt Upson