簡體   English   中英

將誤差線添加到折線圖中

[英]Adding error bar to line graph

我對R很陌生,我設法使用'plot'創建了一個圖,但是我忘記了誤差線,並且我想添加它們而不重做整個事情。 有人知道捷徑嗎?

我手工計算平均值,因為數據集很小。 這是我使用的原始數據和制作圖形的代碼。 我想我需要讓R計算平均值和標准誤差,但是當我嘗試時,我無法使圖形看起來相同。

# Pnem mean occurence each year
Plot9Pn <- c(46, 33, 28)
Plot11Pn <- c(20, 18, 10)
Plot14Pn <- c(34, 28, 26)
Plot15Pn <- c(57, 33, 12)


# Pram mean occurence each year
Plot9Pr <- c(30, 46, 95)
Plot11Pr <- c(8, 11, 14)
Plot14Pr <- c(10, 46, 46)
Plot15Pr <- c(15, 37, 110)


#hand calculated means across plots for each year- to be used in line graph
# Pn2009 <- 39.25
# Pn2010 <- 30.5
# Pn2011 <- 19

# Pr2009 <- 15.75
# Pr2010 <- 35
# Pr2011 <- 66.25


# Define 2 vectors
Pn <- c(39.25, 30.5, 19)
Pr <- c(15.75, 35, 66.25)

g_range <- range(0, Pn,Pr)

plot(Pr, type="o", pch=1, lty=1, col="red", ylim=g_range, 
 axes=FALSE, ann=FALSE)

lines(Pn, type="o", pch=2, lty=1, col="blue", ylim=g_range, 
  axes=FALSE, ann=FALSE)

# Make x axis using 2009-2011 labels
axis(1, at=1:3, lab=c("2009","2010","2011"))

# Create a title with a red, bold/italic font
title(main="Mean Yearly Pathogen Levels in Pilarcitos ", col.main="red", font.main=4)

# Label the x and y axes with dark green text

title(xlab="Year", col.lab=rgb(0,0.5,0))
title(ylab="# Positive", col.lab=rgb(0,0.5,0))

# Make y axis with horizontal labels that display ticks at 
# every 4 marks. 4*0:g_range[2] is equivalent to c(0,4,8,12).
axis(2, las=1, at=8*0:g_range[2])

# Create box around plot
box()

# Create a legend at (1, g_range[2]) that is slightly smaller 
# (cex) and uses the same line colors and points used by 
# the actual plots 

legend(1, g_range[2], c("P.ramorum","P. nemorosa"), cex=0.8, 
   col=c("red","blue"), pch=1:2, lty=1);
box()

我認為您可能誤算了Pn2010的平均值。

但是如果您還要手動計算標准偏差

Pr.sd <- c(9.946, 16.553, 44.275)
Pn.sd <- c(15.903, 7.071, 9.309

您可以使用添加錯誤欄

arrows(x0=1:3, y0=Pr-Pr.sd, y1=Pr+Pr.sd, 
    code=3, angle=90, length=.1, col="red")
arrows(x0=1:3, y0=Pn-Pn.sd, y1=Pn+Pn.sd, 
    code=3, angle=90, length=.1, col="blue")

在這里,我只添加+/- 1 sd。 您可以根據需要計算它們。 您可能會考慮抵消點,因為它看起來並不特別好。

arrows功能是基本的圖形功能,因此它將與您已有的繪圖代碼一起使用。 但是,為了使事情在未來更容易,你可能要考慮使用繪圖軟件包一樣ggplot2lattice的這兩個化妝用多組更容易和繪圖的ggplot使得添加誤差線,以及更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM