Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Y axis out of plotting region with barplot() in R

Tags:

plot

r

I'm having problems getting the y axis on a horizontal barplot() within the plotting region. See this example, I thought that using ylim and/or yaxp would stop this going off the plotting region, but it doesn't seem to work.

I've tried to reproduce the set up I've got:

x <- matrix(abs(rnorm(34)), nrow = 34, ncol = 3)
rownames(x) <- c(seq(0,6600,200))
barplot(x[,3], horiz=TRUE, space = 0.4, main = "Title", las=1, cex.names=0.8, ylab="y label")

But the axis goes of the plotting region if I add ylim:

barplot(x[,3], horiz=TRUE, space = 0.4, ylim = c(0,25), yaxp=c(0,25,1), main = "Title", las=1, cex.names=0.8, ylab="y label")
like image 518
CCID Avatar asked Feb 26 '23 21:02

CCID


2 Answers

For some (strange?) reason, barplot has xpd = TRUE by default, setting this to false will cause it to clip like most plot functions:

barplot(x[,3], horiz=TRUE, space = 0.4, ylim = c(0,25), yaxp=c(0,25,1),
        main = "Title", las = 1, cex.names = 0.8, ylab = "y label", xpd = FALSE)
like image 160
Charles Avatar answered Mar 16 '23 06:03

Charles


The key here is to forget about ylim when using barplot and instead just send the desired plotting range in the data:

barplot(x[1:25,3], horiz=TRUE,  space = 0.4,  yaxp=c(0,25,1), main = "Title", las=1,  
          cex.names=0.8, ylab="y label")

Also note that indexing in R starts at 1 and not at 0 as it might in some other languages.

like image 26
IRTFM Avatar answered Mar 16 '23 06:03

IRTFM