1

I have the following code in R:

dat <- as.matrix(read.table(text ="2011 2012 2013 2014
            A -330.2165 500.53 730.75 -130.0941
            R 2036.32 1155.91 345.81 218.0350", header=TRUE))

pts <- pretty(c(min(dat),max(dat)))

barplot(dat,
        ylim=c(min(pts),max(pts)),
        col=c("mediumvioletred","midnightblue"),    
        legend.text=c("Appropriation","Receipts"),
        args.legend = list(x="topleft", bty="n"))

The problem is that all of the appropriation (A) values should be "mediumvioletred", while all of the receipts values (R) should be "midnightblue". Instead what happens is that if A values are negative, they are colored "midnightblue" as well.

Does anyone know how to fix this? Or at least, to specify a color for each point graphed?

I have found many solutions on coloring in bar graphs - but not stacked bar graphs. This post came this closest: Conditional Barchart coloring with a vector in R, but still did not solve my issue.

Community
  • 1
  • 1
B. Queen
  • 13
  • 3

1 Answers1

0

Though not entirely satisfying, you can do this with some additional steps:

# get the size of first bar (blue) with positive second bar added on
# first plot (blue)
barplot(firstBar,
        ylim=c(min(pts),max(pts)),
        col="midnightblue")
# add second plot (red)
barplot(dat[1,], col="mediumvioletred", add=TRUE)
# add legend
legend(x="topright", legend=c("Receipts", "Appropriation"),
       fill=c("midnightblue", "mediumvioletred"), bty="n")

The second step adds the first row on top of the second row.

As an alternative, you can use beside=TRUE in have adjacent bar plots rather than stacked ones:

barplot(dat,
        col=c("mediumvioletred", "midnightblue"),    
        legend.text=c("Appropriation","Receipts"),
        args.legend = list(x="topleft", bty="n"), beside=TRUE)
lmo
  • 37,904
  • 9
  • 56
  • 69