重现ggplot2 geom_linerange()示例

时间:2013-04-21 02:10:20

标签: r 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个线段,其中一个对应于bias变量的25个cnd变量的25个,第50个和第75个百分位数。

这是我的代码:

p <- ggplot(outbtu,aes(factor(cnd),bias,
                   ymin=quantile(bias,.25),
                   ymax=quantile(bias,.75)))
p <- p + geom_linerange()
p + geom_pointrange()

老实说,我不知道我是否接近,这正是我可以从ggplot帮助页面中找到的。提前谢谢!

2 个答案:

答案 0 :(得分:3)

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)

答案 1 :(得分:2)

您需要单独计算所有统计数据,然后绘制获得的中位数和分位数值。否则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()
相关问题