Question

When plotting a stacked barplot using {graphics} I get a problem with the x-axis not scaling correctly, the ticks aren't aligned to the bars properly, leaving the axis too short.

# dummy data
mat <- structure(c(0L, 5L, 7L, 10L, 12L, 14L, 16L, 18L, 20L, 22L, 24L, 
                26L, 28L, 30L, 32L, 34L, 36L, 38L, 40L, 42L, 44L, 46L, 48L, 50L, 
                52L, 54L, 56L, 58L, 60L, 62L, 63L, 64L, 0L, 0L, 0L, 3L, 0L, 0L, 
                1L, 0L, 0L, 0L, 5L, 0L, 1L, 4L, 0L, 9L, 0L, 0L, 1L, 0L, 8L, 0L, 
                7L, 0L, 1L, 1L, 6L, 0L, 1L, 3L, 4L, 0L, 1L, 1L, 5L, 6L, 1L, 6L, 
                0L, 0L, 5L, 4L, 1L, 8L, 0L, 1L, 1L, 3L, 1L, 3L, 1L, 0L, 1L, 1L, 
                1L, 1L, 0L, 3L, 3L, 5L, 4L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 
                0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
                0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 6L, 0L, 
                11L, 0L, 7L, 0L, 6L, 0L, 0L, 5L, 4L, 0L, 1L, 0L, 1L, 0L, 0L, 
                1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 9L, 0L), .Dim = c(32L, 5L
                ), .Dimnames = list(NULL, c("Time", "Var1", "Var2", "Var3", "Var4"
                )))

# barplot
barplot(t(mat[,2:4]), beside=F, legend=levels(mat), col=c("blue",'red','forestgreen','purple'))

# manually assign x-axis
axis(1,at=c(1:32),labels=mat[,1])

Any pointers on this would be highly appreciated. Im not interested in a ggplot2 solution. Thanks!

enter image description here

Was it helpful?

Solution

For your axis, get the coordinates of the barplots first.

bp <-barplot(t(mat[,2:5]), beside=F, 
             legend = levels(mat), col = c("blue",'red','forestgreen','purple'))

Now use bp for x-tick labels

axis(1,at=bp,labels=mat[,1])

The resulting plot enter image description here

Also, if you play with the width of your plot window/device, you can get all the labels.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top