b4154
b4154

Reputation: 383

Draw longer x- and y-axes with barplot() without setting inner box with box()

Purpose:

Create a plot similar the following sketch: enter image description here.

y-axe should have also negative values. So x- and y-axes should be increased and arrows added to the end.

Code:

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

Upvotes: 0

Views: 53

Answers (1)

Roman
Roman

Reputation: 17648

As already mentioned in the comments use xlim and ylim and the arrow function. I removed redundant code.

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

Upvotes: 2

Related Questions