ss0208535 ss0208535 - 3 months ago 20
R Question

ggplot2 graph and overriding

I have recently started using

ggplot2
so, I once again apologize for posting basic question.

I read about this code in one of the help pages. This code nicely plots line graph and the average with red dot:

ggplot(mpg, aes(trans, cty)) +
geom_point() +
stat_summary(geom = "point", fun.y = "mean", colour = "red", size = 4)


I thought of simplifying this a bit by overriding the contents of
geom_point()
and using
stat="summary"


ggplot(mpg, aes(trans, cty)) +
geom_point(stat = "summary", fun.y = "mean", colour = "red", size = 4) +


However, the above code doesn't work. Can someone please help me why above code doesn't work? Specifically, it only plots the red dot (mean point). I don't see the scatterplot although I have used
geom_point()

Pj_ Pj_
Answer

Because ggplot() defines aes(), but you are overriding them using the geom layer.

In the first case, geom_point() completes the plotting of the points, and stat_summary() did the part of adding summary statistics layer to your graph.

But, when you define stat = "summary", you tell geom_point() to plot summary statistics instead of the data points.

Head over the ggplot2 documentation and read how mapping works within this ecosystem: http://docs.ggplot2.org/current/

Comments