问题
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
回答1:
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"))
来源:https://stackoverflow.com/questions/38719788/how-to-show-null-data-in-barplot-r