0
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy))

ggplot(mpg, aes(x=displ,y=hwy))+geom_point()

What is the difference between the two command lines, both of them have the same output?

2
  • There is also a variant of the second line: ggplot(mpg) + aes(x=displ,y=hwy) + geom_point()
    – Uwe
    Mar 12, 2020 at 7:51
  • Another option to call empty plot: ggplot() + geom_point(mapping = aes(x = displ, y = hwy), data = mpg) In short, 1st one is useful when we use the same data for all layers, 2nd is better when we use different data for each layer.
    – zx8754
    Mar 12, 2020 at 8:14

1 Answer 1

2

Both line do the same with your code.

The difference is, in line 2 you pass all arguments to the ggplot function and the aesthetic mapping will stay the same for every geom_ you add to the plot.

It's shorter if you want to reuse the mapping for other geoms, like geom_line(). Line one is more flexible if you wish to add other geoms to the same plot, as you only passed the data to the ggplot function but did the mapping directly in the geom_point function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.