![](/img/trans.png)
[英]How to create a function to display the 25th and 75th percentile (IQR) in table1 package
[英]How to create a boxplot in R, with box representing the 15th and 85th percentiles, rather than the default 25th and 75th?
我只是使用此內置數據集來解釋我想做的事情,因為我的數據基本上是相同的。 使用bwplot
的標准箱線圖顯然bwplot
了第25個和第75個百分位數作為框的頂部和底部。
我有辦法改變箱形圖,使箱形的頂部和底部分別是每個系數的第85和15個百分點嗎? 如果這不可能-是否有辦法將它們分別表示為每個因子上方的線?
library(MASS)
data <- ChickWeight[,c("Diet", "weight")]
bwplot(data$weight~data$Diet)
我還希望能夠繪制靜態范圍作為圖的背景(例如,介於150到250之間的陰影區域)-如何做到這一點?
預先致歉,因為我對R還是陌生的。非常感謝您對這個簡單任務的任何幫助,我發現很多R文檔都很難理解。
bwplot
使用函數fivenum
來生成箱線圖分位數。 您可以通過制作自己的功能boxplot.stats
版本來更改此boxplot.stats
。 在這里,我只更改了一行,您可以看到它已被注釋掉。 您可以在my.panel
函數中添加所需的陰影:
library(MASS)
library(lattice)
my.boxplot.stats <- function (x, coef = 1.5, do.conf = TRUE, do.out = TRUE) {
if (coef < 0)
stop("'coef' must not be negative")
nna <- !is.na(x)
n <- sum(nna)
#stats <- stats::fivenum(x, na.rm = TRUE)
stats <- quantile(x, probs = c(0.0, 0.15, 0.5, 0.85, 1.0), na.rm = TRUE)
iqr <- diff(stats[c(2, 4)])
if (coef == 0)
do.out <- FALSE
else {
out <- if (!is.na(iqr)) {
x < (stats[2L] - coef * iqr) | x > (stats[4L] + coef *
iqr)
}
else !is.finite(x)
if (any(out[nna], na.rm = TRUE))
stats[c(1, 5)] <- range(x[!out], na.rm = TRUE)
}
conf <- if (do.conf)
stats[3L] + c(-1.58, 1.58) * iqr/sqrt(n)
list(stats = stats, n = n, conf = conf, out = if (do.out) x[out &
nna] else numeric())
}
my.panel <- function (x,y,...) {
panel.rect(xleft = 0, xright = 5, ybottom = 150, ytop = 250, col="lightgrey", border = 0)
panel.bwplot(x, y, ...)
}
data <- ChickWeight[,c("Diet", "weight")]
bwplot(data$weight~data$Diet, stats = my.boxplot.stats, panel= my.panel)
在此處查看答案: 在R中的箱圖中添加不同的百分位數
基本上,您首先需要手動計算分位數並手動添加線段。 這是最可靠的解決方案。
另外,您可以使用ggplot2快速執行此操作,而不會出現異常值。 如果確實需要,可以手動添加離群值。
library(ggplot2)
library(MASS)
library(plyr)
data <- ChickWeight[,c("Diet", "weight")]
data2 <- ddply(data,.(Diet),
summarize,
ymin = min(weight),
ymax = max(weight),
middle = median(weight),
lower = quantile(weight,0.15),
upper = quantile(weight,0.85))
ggplot(data2,aes(x = Diet)) + geom_boxplot(aes(ymin = ymin,ymax = ymax,middle = middle,upper = upper,lower= lower), stat = 'identity')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.