ss0208535 ss0208535 - 3 months ago 17
R Question

using fun.y in ggplot

I am an absolute beginner. So, I apologize for asking basic question. I am trying to plot the minimum value in my dataset. I looked at the following page (changing y scale when using fun.y ggplot) and didn't find the solution.

Here's the first code: this works well. It plotsa red dot at the mean.

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


This one doesn't work. Can someone please help me?

ggplot(mpg, aes(trans, cty)) +
geom_point() +
stat_summary(geom = "point", fun.ymin = min, colour = "red", size = 50)


I am not sure what's going on.

Answer

In stat_summary, what you plot depends on the geom you choose. You seem to want to plot points, so you chose geom = 'point'. A point only has a single y value, so you only fun.y will be used by the summary.

There are other arguments, fun.ymin and fun.ymax. This isn't super clear in the documentation, but they needed if you are using more complicated geoms, for example geom = 'pointrange' which plots a point and a vertical bar, e.g.

ggplot(mpg, aes(trans, cty)) +
  geom_point() +
  stat_summary(geom = 'pointrange', fun.ymin = min, fun.ymax = max, fun.y = mean, colour = "red", size = 1)

In this case, ggplot is coded in an adaptable way so that you can pass the name of a function as a character string, fun.ymin = 'min', or you can pass the function directly, fun.ymin = min.

Comments