1

I want to draw a barplot with in axis x the number of months and in axis y the value of a variable. The variable can be null for some months. How can I coerce the axis x to always show the 12 months?

With V a data frame like:

    month variable
    1  125
    2  45 
    3  158
    4  15
    5  58
    6  78
    7  89
    9  15
    10 85
    11 799
    12 55

Here in August (month 8) the variable is 0.

bp <- barplot(V[,2],  axes = FALSE)
axis(1, at = bp, labels=c("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"))

Thanks

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
A.Alfredo
  • 21
  • 5
  • Try to replace `NULL` values by `NA` – jlesuffleur Aug 02 '16 at 12:06
  • It's hard to give you a specific answer without knowing what `V` looks like. Can you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) please? – Weihuang Wong Aug 02 '16 at 12:33

1 Answers1

2

You need to pad an NA at August (month 8). Simply use

bp <- barplot(append(V[,2], NA, 7),  axes = FALSE)
axis(1, at = bp, labels=c("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"))

More generally I would do this:

x <- rep(NA, 12)
x[V$month] <- V$variable
bp <- barplot(x, axes = FALSE)
axis(1, at = bp, labels=c("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"))

enter image description here

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • A more general solution for the padding is to create a new data frame with all 12 months: `df <- data.frame(month=1:12)`. Then merge `V` with `df` (where `V` is your original dataframe, possibly with some missing months): `V <- merge(df, V, all.x=TRUE)`. Now all the missing months will have corresponding `NA`s in `V`. – Weihuang Wong Aug 02 '16 at 13:21
  • 1
    Or more parsimoniously: `bp <- barplot(ifelse(1:12 %in% V$month, V$variable, NA), axes=FALSE)`. – Weihuang Wong Aug 02 '16 at 13:33