在小图中设置轴标签和刻度线的不同位置 [英] Set different positions of axis labels and tick marks in a barplot
问题描述
我想重新对齐/偏移小节图的x轴和相关的刻度线.这应该很简单,但是我很难找到答案.以下是一些具有24个类别的示例数据.
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)
我还可以使用以下方法移动整个x轴(标签和刻度线)以与条形图的外部对齐(尽管现在无法将最后一个条形图合并到该轴中):
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)
虽然我希望x轴和相关的刻度线与条形边界对齐(即,在条形的两边而不是在中心的刻度线),但我希望x轴标签保持在酒吧的中点.有一个简单的方法可以做到这一点吗?
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?
推荐答案
这是您要寻找的吗?
# 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)
这篇关于在小图中设置轴标签和刻度线的不同位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!