2013-10-27 59 views
2

我用R中的彩色錯誤條繪製數據。我想在圖例中顯示「樣例錯誤條」(使用圖中的顏色),但是如何?如何在R的圖例中顯示示例錯誤欄?

library("Hmisc") 

d1=data.frame(x=c(1,2,3,4,5), meanY=c(1,2,3,4,5), sdY=c(1,1,1,1,1)) 
d2=data.frame(x=c(1,2,3,4,5), meanY=c(2.1,3.3,4.1,5.2,6.1), sdY=c(1.3,1.2,1.4,1.1,1.2)) 

plot(1, 1, type="n", xlab="X values", ylab="Y values", xlim=c(1,5), ylim=c(0,7)) 
with (data = d1, expr = Hmisc::errbar(x, meanY, meanY+sdY, meanY-sdY, pch=1, cex=.5, cap=.0025, add=T, errbar.col="red")) 
with (data = d2, expr = Hmisc::errbar(x, meanY, meanY+sdY, meanY-sdY, pch=1, cex=.5, cap=.0025, add=T, errbar.col="green")) 

legend(x="bottomright", legend=c("d1", "d2"), pch=1, pt.cex=.5) 

回答

2

傳說有些手工打造...

# bind data together to simplify plot code 
df <- rbind(d1, d2) 

# plot 
with(df, 
    errbar(x = x + c(rep(0.05, nrow(d1)), rep(-0.05, nrow(d2)), # dodge points to avoid overplotting 
      y = meanY, 
      yplus = meanY + sdY, 
      yminus = meanY - sdY, 
      pch = 1, cex = 0.5, cap = .0025, 
      errbar.col = rep(c("red", "green"), times = c(nrow(d1), nrow(d2))), 
      xlab = "X values", ylab = "Y values", 
      xlim = c(1, 5), ylim = c(0, 7))) 


# create data for legend 
df_legend <- data.frame(x <- c(4.5, 4.5), 
         y <- c(1, 2), 
         sdy <- c(0.3, 0.3)) 

# add symbols to legend 
with(df_legend, 
    errbar(x = x, 
     y = y, 
     yplus = y + sdy, 
     yminus = y - sdy, 
     pch = 1, cex =.5, cap = .0025, 
     errbar.col = c("red", "green"), 
     add = TRUE)) 

# add text to legend 
with(df_legend, 
    text(x = x + 0.2, 
      y = y, 
      labels = c("d2", "d1"))) 

# add box 
with(df_legend, 
    rect(xleft = x - 0.2, 
      ybottom = y[1] - 0.5, 
      xright = x + 0.4, 
      ytop = y[2] + 0.5)) 

enter image description here

+0

我想有一個更簡單的方法。現在我使用半透明多邊形來繪製誤差/標準偏差。 http://fenon.de/transluzente-polygone-in-r-plots-einzeichnen/ –