Passing extra parameters into the stat function

Viewed 201

I'm learning R and ggplot2. According to the instructions, geom and stat are usually inter-changable as a geom has a default stat and a stat has a default geom.

My exercise is to create a plot in 3 ways: with stat, manually, and with geom_pointrange. I'm stuck at the third part:

library("tidyverse")

# With stat_summary
ggplot(data = diamonds) +
  stat_summary(
    mapping = aes(x = cut, y = depth),
    fun.min = min,
    fun.max = max,
    fun = median
  )

# Manually
diamonds_summary = diamonds %>% 
  group_by(cut) %>% 
  summarize(p = median(depth), lower = min(depth), upper = max(depth))

ggplot(diamonds_summary) +
  geom_pointrange(
    mapping = aes(x = cut, y = p, ymin = lower, ymax = upper)
  )

# With geom_pointrange and stat
ggplot(data = diamonds) +
  geom_pointrange(
    mapping = aes(x = cut, y = median(depth)),
    stat = "summary"
  )
# Warning: No summary function supplied, defaulting to `mean_se()`

How can I pass two summary functions (min and max) to the function identified by the stat param?

All three solutions should produce the following output:

enter image description here

1 Answers

When you sepcify stat="summary", it still needs to know how to summarize your values. The default is to use the mean with standard errors. But you want medians with min and max values. You can write your own summary function

median_min_max <- function(x) {
  data.frame(y=median(x), ymin=min(x), ymax=max(x))
}

And then pass that to your pointrange layer via the fun.data= parameter.

ggplot(data = diamonds) +
  geom_pointrange(
    mapping = aes(x = cut, y = depth),
    stat = "summary", fun.data = median_min_max
  )

This will give you a plot that matches the one you created from your summarized data.

ggplot does have a median_hilow summary function but that uses the Hmisc::smedian.hilow function which uses quantiles based on a confidence inteval rather than min/max values.

Related