2017-04-13 124 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