-->

R barplot Y-axis scale too short

2020-05-30 02:55发布

问题:

I'm trying to generate a barplot, but the y-axis scale is too short. Here's my code:

barplot(as.matrix(dat), log="y", ylim=c(10000,100000000), beside=TRUE,
        ylab = "Number of reads", col = c("gray","black","white"))

It leaves the room for the axis (as per ylim), but doesn't fill in the actual axis. I've been through ?barplot and tried a few things (from googling around I thought xpd = F, yaxs = c(10000,10000000,5) should work, but it didn't).

I know it's a minor thing, but it's exactly the kind of problem I get stuck on for ages, instead of actually working, so any help would be much appreciated!

Edit: Cheers for the input guys!

I did initially plot without ylim, but it ends up with an even more bizarre axis (with the same problem); I actually picked my ylim values to give it a nicer spaced axis.

Here's the data:

dat <- read.table(text="D2,D3n,D3m,D4n,D4m
21234722,34262282,31920464,25486357,20712943
35343,64403,22537,39934,46547
126646,312286,101105,81537,76944", header=TRUE, sep=",")

Edit 2: @DWin had it right - I updated my R, and now it plots fine - thanks everyone!

回答1:

I see you try to set ylim but you give bad values. This will change the scale of the plot (like a zoom). For example see this:

par(mfrow=c(2,1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
r <- barplot(tN, col = rainbow(20),main='short y axis')

Another option is to plot without axes and set them manually using axis and usr:

require(grDevices) # for colours
par(mfrow=c(1,1))
r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
usr <- par("usr")
par(usr=c(usr[1:2], 0, 20))
axis(2,at=seq(0,20,5))



回答2:

Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

# default y-axis
barplot(dat, beside=TRUE)

# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))

The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.



回答3:

barplot(data)

barplot(data, yaxp=c(0, max(data), 5))

yaxp=c(minY-axis, maxY-axis, Interval)