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
)
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)
ggplot will apply fun.min to its y value (which was specified as depth). The default function that is used is min, but defining fun.min like this allows the use of a different function. ggplot knows to apply fun.min to its y value.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)