Question

I would like to realign/offset the x-axis and associated tick marks of a barplot. This should be simple but I am having trouble finding an answer. Below is some example data with 24 categories.

xval = c(1:24)
count = c(0.03,0.03,0.08,0.06,0.11,0.4,0.3,0.5,0.5,0.6,0.4,0.1,0.1,0.4,0.2,0.1,0.06,0.05,0.03,0.02,0.01,0.03,0.01,0.02)
df = as.data.frame(cbind(xval, count))

I can easily produce a barplot with tick marks aligned at the bar midpoints using the below code:

mp <- barplot(df$count, space=0, axes=FALSE) 
axis(side=2, pos=-0.2)
axis(side=1, at =mp, labels=df$xval)

I can also shift the entire x-axis (labels and ticks) to align with the outside of bars using the below (although this now fails to incorporate the last bar into the axis):

axis(side=1, at =mp-0.5, labels=df$xval)

While I would like the x-axis and associated tick marks to be aligned with the bar boundaries (i.e. a tick mark on either side of the bar instead of in the centre), I want the x-axis labels to remain at the bar midpoints. Is there an easy way to achieve this?

Was it helpful?

Solution

Is this what you are looking for?

# create positions for tick marks, one more than number of bars
at_tick <- seq_len(length(count) + 1)

# plot without axes
barplot(count, space = 0, axes = FALSE) 

# add y-axis
axis(side = 2, pos = -0.2)

# add x-axis with offset positions, with ticks, but without labels.
axis(side = 1, at = at_tick - 1, labels = FALSE)

# add x-axis with centered position, with labels, but without ticks.
axis(side = 1, at = seq_along(count) - 0.5, tick = FALSE, labels = xval)

enter image description here

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