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?
Add tick marks on an axisClick Add Chart Element > Axes > More Axis Options. On the Format Axis pane, expand Tick Marks, and then click options for major and minor tick mark types. After you add tick marks, you can change the intervals between the tick marks by changing the value in the Interval between marks box.
Barplots in R programming language can be created using the barplot() method. It takes as input a matrix or vector of values. The bar heights are equivalent to the values contained in the vector.
The tick labels are the labels that you see next to each tick mark. The tick values are the locations along the x-axis where the tick marks appear. Set the values using the xticks function. Set the corresponding labels using the xticklabels function.
xticks( ticks ) sets the x-axis tick values, which are the locations along the x-axis where the tick marks appear. Specify ticks as a vector of increasing values; for example, [0 2 4 6] . This command affects the current axes. xt = xticks returns the current x-axis tick values as a vector.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With