R:在几个图中,在轴缩放时,在yline y = 0处定义ylim

时间:2014-11-01 20:31:10

标签: r plot axis scaling

我正在绘制如下代码中的几个图(示例代码应生成三个不同的图形)。我遇到的问题是y轴的缩放。

我的问题:我如何定义我的ylimit,以便在我的图中始终可以看到y = 0处的abline?

此时y轴会自动缩放。我正在寻找baseR的解决方案。

xy <- structure(list(NAME = structure(c(2L, 3L, 1L, 1L), .Label = c("CISCO","JOHN", "STEPH"), class = "factor"), ID = c(41L, 49L, 87L, 87L), X_START_YEAR = c(1965L, 1948L, 1959L, 2003L), Y_START_VALUE = c(940L,-1760L, 110L, 866L), X_END_YEAR = c(2005L, 2000L, 2000L, 2007L), Y_END_VALUE = c(940L, -1760L, 110L, 866L), LC = structure(c(1L,1L, 2L, 2L), .Label = c("CA", "US"), class = "factor")), .Names = c("NAME", "ID", "X_START_YEAR", "Y_START_VALUE", "X_END_YEAR", "Y_END_VALUE","LC"), class = "data.frame", row.names = c(NA, -4L))

ind <- split(xy,xy$ID) # split by ID for different plots

# Plots
for (i in ind){
  xx = unlist(i[,grep('X_',colnames(i))])
  yy = unlist(i[,grep('Y_',colnames(i))])    
  fname <- paste0(i[1, 'ID'],'.png')
  png(fname, width=1679, height=1165, res=150)

  # Define ylim so that y=0 (abline) is always in plots

  par(mar=c(6,8,6,5))
  plot(xx,yy,type='n',main=unique(i[,1]), xlab="Time [Years]", ylab="Value [mm]") 
  abline(h=0, col = "gray60")
  i <- i[,-1]
  segments(i[,2],i[,3],i[,4],i[,5],lwd=2)
  points(xx, yy, pch=21, bg='white', cex=0.8)
  dev.off()
}  

1 个答案:

答案 0 :(得分:2)

只需确保包含一些高于/低于0的数字,并使用range()给出高于和低于零的最大值和最小值。怎么样包括

 ylim = range(c(yy,-.5,.5))

作为plot()

的参数