[英]Adding point in geom_linerange() and reduce the gap in R ggplot2
[英]Reproducing a ggplot2 geom_linerange() example
我正在嘗試制作一個最終看起來像這樣的情節:
但是,我希望每行的端點代表每組數字的第25個百分點(在底部)和第75個百分點(在頂部)。 中間的點應為中間值。 我可以使用geom_boxplot()
從這些數據繪制箱形圖,但是我認為這樣看起來會更好。 無論如何,我無法完成這項工作。 現在,我收到此錯誤消息:
Warning message:
In data.frame(x = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, :
row names were found from a short variable and have been discarded
我的數據如下所示:
> str(outbtu)
'data.frame': 86400 obs. of 2 variables:
$ bias: num -0.248 -0.759 -0.471 -0.304 -0.358 ...
$ cnd : int 1 1 1 1 1 1 1 1 1 1 ...
> outbtu[1:10,]
bias cnd
1 -0.24756150 1
2 -0.75906264 1
3 -0.47142178 1
4 -0.30395184 1
5 -0.35756559 1
6 0.04072695 1
7 -0.45026249 1
8 -0.20509166 1
9 -0.24816174 1
10 -0.01581920 1
最終cnd
到達27,但是27個cnd
值中的每個值都有3200個觀測值,因此您顯然在這里看不到它。 我想要此圖上的27條線段,分別對應於27個cnd
值的bias
變量的第cnd
和75%。
這是我的代碼:
p <- ggplot(outbtu,aes(factor(cnd),bias,
ymin=quantile(bias,.25),
ymax=quantile(bias,.75)))
p <- p + geom_linerange()
p + geom_pointrange()
老實說,我什至不知道自己是否接近,這就是我可以從ggplot幫助頁面中找到的內容。 提前致謝!
set.seed(42)
DF <- data.frame(bias=rnorm(2700),cnd=1:27)
DF$cnd <- factor(DF$cnd)
library(ggplot2)
ggplot(DF,aes(x=cnd,y=bias,colour=cnd)) +
stat_summary(fun.data=function(x) {
res <- quantile(x,probs=c(0.25,0.5,0.75))
names(res)<-c("ymin","y","ymax")
res})
或更短:
ggplot(DF,aes(x=cnd,y=bias,colour=cnd)) +
stat_summary(fun.data=median_hilow,conf.int=0.5)
您需要分別計算所有統計信息,然后繪制獲得的中位數和分位數。 否則, ymin=quantile(bias,.25)
返回的向量大於factor(cnd)
大小。
這是一個例子
# Generate sample data
df <- data.frame(a=rnorm(100), b=sample(1:5, 100, replace=T))
# Calculate statistics for each group of b values
df2 <- t(sapply(unique(df$b), function(x) {
s <- summary(df[df$b == x, "a"])[c(2,3,5)]
c(x, s)
}))
# Convert output matrix to data.frame since ggplot works only with data.frames
df2 <- as.data.frame(df2)
# Rename column names for clarity
colnames(df2) <- c("b", "Q1", "Median", "Q3")
# Draw obtained values
ggplot(df2, aes(x=b, y=Median, ymin=Q1, ymax=Q3)) + geom_pointrange()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.