使用barplot()绘制更长的x轴和y轴,而不用框()

时间:2015-12-14 08:46:14

标签: r bar-chart

目的:

创建类似于以下草图的图:enter image description here

y-ax也应该有负值。因此,应增加x轴和y轴,并在最后添加箭头。

代码:

par(mai=c(2, 1, 1, 1), lwd=2)
barplot(as.numeric(c(2, 4, 1, 6)), col = c("lightblue"), main="Bar plot",
        names.arg=c("This is bar 1...1","This is bar 1...2",
                    "This is bar 1...3","This is bar 1...4"),
        xpd=TRUE, las=2, lwd=2, axes=TRUE, axis.lty=1,
        cex.axis=1, cex.names=1, cex.main=1)
axis(4, 0:6)
box(which="outer", lty="solid")

1 个答案:

答案 0 :(得分:2)

正如评论中已经提到的那样,使用xlim和ylim以及箭头函数。 我删除了冗余代码。

par(mai=c(2, 1, 1, 1), lwd=2)
LAB <- c("This is bar 1...1","This is bar 1...2",
         "This is bar 1...3","This is bar 1...4")
# save the barplot to extract the x position of the bars
a <- barplot(as.numeric(c(2, 4, 1, 6)), col = c("lightblue"), main="Bar plot", las=2,yaxt="n",xaxt="n",
  ylim=c(-5,7),xlim=c(0,5))
# arrows
arrows(0.1,-2,0.1,6.5,col='red')
arrows(0,0,5,0,col='red')
# ticks and labels
axis(2,1:4,pos=0.1,lwd=2,col="red")
axis(1,at=a,labels = LAB,pos=0,lwd=2,col="red")