[英]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
功能是基本的图形功能,因此它将与您已有的绘图代码一起使用。 但是,为了使事情在未来更容易,你可能要考虑使用绘图软件包一样ggplot2
或lattice
的这两个化妆用多组更容易和绘图的ggplot
使得添加误差线,以及更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.