2017-04-13 72 views
1

我想在一个图中结合两个变量, 一个作为geom_pointrange [因为我需要最小和最大表示(置信区间2.5%和97.5%及其中值(50%)) ]结合两个变量ggplot:geom_pointrange和geom_point

其他变量是geom_point,其他结石的中位数由

我发现ggplot使这些陈述,但我还没有得到它在一起,通过:

#inputs 
x <- seq(1:10) 
n <- length(x) 
yone <- 2 * runif(n) 
ytwo <- runif(n) 
ythree <- ytwo * 0.2 
yfour <- ytwo * 2 

df <- data.frame(x, yone, ytwo, ythree, yfour); df 


library (ggplot2) 

#yone and ytwo must be points 
#ythree and yfour are min and max confidence interval (vertical line) 

ggplot(df, aes(x, y = value, color = variable)) + 
geom_pointrange(aes(ymin = ythree, ymax = yfour)) + 
geom_point(aes(y = yone, col = "yone")) + 
geom_point(aes(y = ytwo, col = "ytwo")) + 
geom_line(aes(y = yfour)) 

谁能帮我请问

+0

应该采取什么结果是什么样子?你能把我们指向一个类似的图形吗?此外,现在您的示例不会运行,因为您提供的数据集不包含“值”或“变量”。 – aosmith

回答

0

下面是一个可能的解决方案,以获得您似乎瞄准的情节类型。我已使用reshape2包来将您的数据转换为长格式。有许多选项可供选择,包括tidyr(聚拢),基准R(重塑)和data.table(熔化)。对于熔化data.frame中的yone行,我已将置信区间设置为NA,因为您没有计算这些行。最后,我已经使用geom_linerangegeom_point而不是geom_pointrange,以便正常处理NA值。

library(ggplot2) 
library(reshape2) 

# Reshape data to long form. 
mdat <- melt(df, id.vars=c("x", "ythree", "yfour")) 

# Set confidence intervals to NA for yone values, 
# values for which you didn't compute CIs. 
mdat[mdat$variable == "yone", c("ythree", "yfour")] <- NA 

p = ggplot(data=mdat, aes(x=x, y=value, colour=variable, ymin=ythree, ymax=yfour)) + 
    geom_linerange() + 
    geom_point(size=3) + 
    geom_line(aes(y=yfour), linetype="dotted") 

ggsave ("plot.png", p, height=4, width=6, dpi=150) 

enter image description here