R: Creating colorized barplot from segments()

238 views Asked by At

I am plotting several hundreds of graphs in a loop using the segments() function. Here is some somple data which creates two graphs.

xy <- structure(list(NAME = structure(c(2L, 2L, 1L, 1L), .Label = c("CISCO", "JOHN"), class = "factor"), ID = c(41L, 41L, 57L, 57L), X_START_YEAR = c(1965L, 1932L, 1998L, 1956L), Y_START_VALUE = c(960L, -45L, 22L, -570L), X_END_YEAR = c(1968L, 1955L, 2002L, 1970L), Y_END_VALUE = c(960L, -45L, 22L, -570L), 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)
# 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)
  par(mar=c(6,8,6,5))
  plot(xx,yy,type='n',main=unique(i[,1]), xlab="Time [Years]", ylab="Value [mm]",ylim = range(c(yy,-.5,.5))) 
  i <- i[,-1]
  segments(i[,2],i[,3],i[,4],i[,5],lwd=2)
  points(xx, yy, pch=21, bg='white', cex=0.8)
  abline(h=0, col = "gray60")
  dev.off()
} 

What I am attempting to do is to change this to a barplot with colorized groups (e.g. every value above 0 is in blue and below 0 in red). I have added a visualisation of what I am trying to achieve from one of the resulting plots.

As I understand from the barplot() function I could use my segments() command (segments(i[,2],i[,3],i[,4],i[,5]) for the setting of width option of each barplot.

My question: Does anyone have an idea how I could change this in order to get the height command out of my data? I am looking for a solution in baseR.

1

There are 1 answers

2
jbaums On BEST ANSWER

You can use rect for this:

lapply(ind, function(x) {
  plot(unlist(x[, c(3, 5)]), unlist(x[, c(4, 6)]), type='n', 
       xlab='Time [Years]', ylab='Value [mm]', main=x[1, 1])
  apply(x, 1, function(y) {
    rect(y[3], min(y[4], 0), y[5], max(y[4], 0), 
         col=if(as.numeric(y[4]) < 0) 'red' else 'blue')
    abline(h=0)
  })
})

enter image description here enter image description here