santoku
santoku

Reputation: 3427

How to use R ggplot stat_summary to plot median and quartiles?

how to change the lower and upper point in this stat summary plot to 25% quartile and 75% quartile?

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

Upvotes: 13

Views: 29431

Answers (3)

mhovd
mhovd

Reputation: 4067

This question already has excellent answers, but I wanted to build on these with more brief solution, as I prefer to keep code for plots short. stat_summary can take custom functions, with support for arguments.

library(ggplot2)

# Define function to calculate IQR at given quantiles
iqr = function(z, lower = 0.25, upper = 0.75) {
  data.frame(
    y = median(z),
    ymin = quantile(z, lower),
    ymax = quantile(z, upper)
  )
}

# Plot standard IQR
ggplot(data = diamonds, mapping = aes(x = cut, y = depth)) + 
  stat_summary(fun.data = iqr)

# Arguments can be accessed with fun.args
ggplot(data = diamonds, mapping = aes(x = cut, y = depth)) + 
  stat_summary(fun.data = iqr, fun.args = list(lower = 0.1, upper = 0.9))

Created on 2022-08-29 by the reprex package (v2.0.0)

Upvotes: 2

mpalanco
mpalanco

Reputation: 13570

Rewriting G5W's solution, using the geom function instead of the stat function:

ggplot(data = diamonds) +
  geom_pointrange(mapping = aes(x = cut, y = depth),
                  stat = "summary",
                  fun.min = function(z) {quantile(z,0.25)},
                  fun.max = function(z) {quantile(z,0.75)},
                  fun = median)

enter image description here

Upvotes: 11

G5W
G5W

Reputation: 37651

ggplot(data = diamonds) + stat_summary(
  mapping = aes(x = cut, y = depth),
  fun.min = function(z) { quantile(z,0.25) },
  fun.max = function(z) { quantile(z,0.75) },
  fun = median)

Diamonds

Upvotes: 20

Related Questions