Set different positions of axis labels and tick marks in a barplot

一个人想着一个人 提交于 2019-12-30 09:45:31

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/19638633/set-different-positions-of-axis-labels-and-tick-marks-in-a-barplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!