2

I would like to plot a stacked bar chart for a matrix of data containing both positive and negative values.

I used the code below and I was expecting all positive values stacked above x-axis and all negative values stacked below x-axis but this is not the case.

  test<-matrix(c(1,-2,-3,4,5,-6),ncol=2)
  colnames(test)=c("A","B")
  rownames(test)=c("x","y","z")
  barplot(test)

If I look at the help I can't find something about this specific topic.

Do I have to use some extra command or extra parameter to achieve that?

Abruzzo Forte e Gentile
  • 14,423
  • 28
  • 99
  • 173
  • I'd like to plot positive and negative two separate stacked bars for the same column. – Abruzzo Forte e Gentile Jan 14 '15 at 17:25
  • 1
    I think this is tricky: You could go with a [ggplot solution](http://stackoverflow.com/questions/13734368/ggplot2-and-a-stacked-bar-chart-with-negative-values) or add `beside=TRUE` , but of course its not stacked. – user20650 Jan 14 '15 at 17:30
  • Experiment with the argument `ylim` . – Carl Witthoft Jan 14 '15 at 17:36
  • Do you know why it is trick with barplot? Worst case I can use 'barchart' from package 'lattice' that seems doing the job if no solution comes up. – Abruzzo Forte e Gentile Jan 14 '15 at 17:36
  • @CarlWitthoft; can you expand on your comment please – user20650 Jan 14 '15 at 17:42
  • Given Carl's comment I am probably missing something but it think you need to make two plots, one with pos counts and one with neg, and use the `add=T` parameter. – user20650 Jan 14 '15 at 17:47
  • @user20650 that wouldn't hurt. As to my previous comment -- the OP should *RTFM* - the meaning of the optional arguments to `barplot` is provided in `?barplot` . – Carl Witthoft Jan 14 '15 at 18:28
  • I am looking into ylim . The documentation says just 'ylim: limits for the y axis'. I do believe that it is hard to understand how this could help solving my problem but I'll keep on reading and investigating. Thanks a lot. – Abruzzo Forte e Gentile Jan 16 '15 at 15:42

1 Answers1

4

A quick (but not the best) workaround:

test1 <- test2 <- test
test1[test1<0] <- 0
test2[test2>0] <- 0
myrange <- c(min(colSums(test2)),max(colSums(test1)))
barplot(test1,ylim=myrange)
barplot(test2,add=TRUE,ylim=rev(myrange))

enter image description here

xb.
  • 1,617
  • 11
  • 16
  • Hi xb! This works and it is ok for me.(and it adds few things I need to look at). Essentially you split the matrix in 2 parts: the negative and the positive and you combined together. I didn't even know that it was possible to do that. Thanks a lot for your help. – Abruzzo Forte e Gentile Jan 16 '15 at 15:40