Why does ggplot change the position of the parameter values of data= and mapping= when using "pipe" operator?

hearted people who clicked in to see this question.I just started learning to use ggplot.

aes(x = displ) |> 

image src

The first command mpg is passed to ggplot as an argument to data =, while the second command is of the same form, but why mpg is passed as an argument to mapping = instead of the incoming aes function as an argument to mapping =?

The error goes like this:


It looks like mpg is being pushed to the side. What is the logic here?

Thank you for your patience.

I try to search on google and asked my friends. But I can’t get an answer. Have I made some mistakes or is this some kind of feature of the R language?

>Solution :

The pipe passes its left hand side to the first unnamed argument of the right hand side. So aes(x = displ) |> ggplot(mpg) is equivalent to ggplot(aes(x = displ), mpg), which in turn is equivalent to ggplot(data = aes(x = displ), mapping = mpg) since that’s the order of ggplot()’s arguments.

If you want to get around this, you can explicitly pass mpg to the data arg:

aes(x = displ) |> 
  ggplot(data = mpg)

or explicitly pass your aes() call to mapping using the pipe placeholder (_):

aes(x = displ) |> 
  ggplot(mpg, mapping = _)

Leave a Reply