Search code examples
rbar-chartaxisaxis-labels

How to change the origin of a barplot?


I have a 2 data set with negative values, so the barplot gives me a plot with bars down. How to set the origin of the y axis in a negative value, in order to obtain bars up?

What I have:

A <- c(-7.3, -2.17, 1.05)
B <- c(-3.69, -5.04, -0.746)
AB <- c(A, B)

barplot(AB, col = c("darkgray","darkgray","darkgray","lightgray","lightgray","lightgray"),#
  names.arg=c("A1", "A2", "A3", "B1", "B2", "B3"))
 legend("bottomright", legend = c("A", "B"), fill = c("darkgray", "lightgray"), horiz = T)

enter image description here

What I want:

enter image description here


Solution

  • new <- abs(-8 - AB)
    
    barplot(new, beside=TRUE, ylim=c(0, 12), yaxt="n",
        col = c("darkgray","darkgray","darkgray","lightgray","lightgray","lightgray"),#
        names.arg=c("A1", "A2", "A3", "B1", "B2", "B3"))
    
    axis(2, seq(0, 12, 2), labels=seq(-8,4,2))
    box(bty="l")
    legend("topright", legend = c("A", "B"), fill = c("darkgray", "lightgray"), horiz = T)
    

    enter image description here