在条形图中设置轴标签和刻度线的不同位置

时间:2013-10-28 15:20:58

标签: r bar-chart axis-labels

我想重新对齐/偏移条形图的x轴和相关的刻度标记。这应该很简单,但我找不到答案。以下是一些包含24个类别的示例数据。

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))

我可以使用以下代码轻松地在条形中点处生成带有刻度标记的条形图:

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

我还可以使用下面的方法移动整个x轴(标签和刻度线)以与条形外部对齐(尽管现在无法将最后一个条形图合并到轴中):

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

虽然我希望x轴和相关的刻度线与条形边界对齐(即条形两侧的刻度线而不是中心),我希望x轴标签保持在酒吧中点。有没有一种简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:7)

这是你在找什么?

# 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