簡體   English   中英

如何使用 R ggplot stat_summary 到 plot 中位數和四分位數?

[英]How to use R ggplot stat_summary to plot median and quartiles?

如何將此統計摘要 plot 中的上下點更改為 25% 四分位數和 75% 四分位數?

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)

鑽石

重寫G5W的解決方案,使用geom函數代替stat函數:

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)

在此處輸入圖片說明

這個問題已經有了很好的答案,但我想用更簡短的解決方案來構建這些,因為我更喜歡保持情節的代碼簡短。 stat_summary可以采用自定義函數,支持 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))

代表 package (v2.0.0) 於 2022 年 8 月 29 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM