[R] Converting xy plot arguments into a point argument and fixed x-axis scaling

David Winsemius dwinsemius at comcast.net
Sat Sep 20 21:55:18 CEST 2014


On Sep 19, 2014, at 1:55 PM, nebulo help wrote:

> Dear all, 
>   
> I have a data.frame xy which I am plotting like in the code below (provided is a small data sample with dummy data that should work). 
>   
> Is there a way how I could convert my xx and yy in the xy plot to a points command so that I could set type='n' and add points afterwards in order to control it better? 
>   
> In the end what I am also aiming for is a fixed x-axis range (e.g. from 1940 to 2014) and if values before 1940 are present the x axis should be automatic. The y axis should always be in the range of the values generated for each plot. 

I would think the general strategy would be to call `plot` and axis (twice) just once and axis (twice) with the xlim, ylim, xlab and ylab set to your specifications and then within the loop, use `points`.


-- 

David.
>   
> Thank you for your help! 
> 
> Kind regards,
> Kurt
>   
> ########################### 
>   
> Here is my code with sample data: 
>   
> # read in sample data 
> xy <- data.frame(NAME=c("NAME1","NAME1","NAME1","NAME2","NAME2","NAME2"),ID=c(87,87,87,199,199,199), X_START_YEAR=c(1984,1986,1984,1899,1909,1924),Y_START_VALUE=c(75,25,-90,-8,-55,-10),X_END_YEAR=c(1986,1994,1999,1909,1924,1927), Y_END_VALUE=c(20,50,-15,-70,-80,-100)) 
>     
> # split data.frame into groups (defined by ID in this case) 
> ind <- split(xy,xy$ID) 
> # plot data by group 
> for (x in ind){ 
>   xx = unlist(x[,grep('X_',colnames(x))]) 
>   yy = unlist(x[,grep('Y_',colnames(x))])     
>     fname <- paste0(x[1, 'ID'], '.png') 
>     png(fname, width=1679, height=1165, res=150) 
>     par(mar=c(6,8,6,5)) 
>     plot(xx, 
>          yy, 
>          main=unique(x[,1]), 
>          xlab="Time [Years]", 
>          ylab="Value [m]") 
>     axis(1, at = seq(1000, 2050, 5), cex.axis=1, labels=FALSE, tcl=-0.3) 
>     axis(2, at = seq(-100000, 100000, 500), cex.axis=1, labels=FALSE, tcl=-0.3) 
>     x <- x[,-1] 
>     segments(x[,2],x[,3],x[,4],x[,5],lwd=2) 
>     dev.off() 
>   }
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list