简体   繁体   中英

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
)
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)

钻石

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)

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM