Reputation: 33
I have the problem that i want to put barplot under a histogram where the barplot of a value is exactly under the certain value of the histogram. Unfortunately the scaling of the histogram is not the same as in the barplot and additionally there is a little gap in the histogram.
Is there a possibility to rearrange that?
# data
set.seed(4566)
a <- rnorm(100)
a <- dnorm(a)*10+1
data <- a
#data plot 2
values <- matrix(,,3)
values[1,1] <- 1
values[1,2] <- 2
values[1,3] <- 3
colnames(values) <- c('Mean','Best 50%','Worst 50%')
# layout boxplot is at the bottom
nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE), height = c(3,1))
par(mar=c(3.1, 3.1, 1.1, 2.1),oma=c(0,2,1,1))
b <- c(0,1,2,3,4,5)
hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue",breaks=b)
barplot(values, horiz=T, xlim=range(0:6),ylim=range(0:3),las=1)
Upvotes: 3
Views: 597
Reputation: 25874
One way is to use the xaxs
parameter within the hist
call
nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE), height = c(3,1))
par(mar=c(3.1, 3.1, 1.1, 2.1),oma=c(0,2,1,1))
hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue", breaks=b, xaxs="i")
barplot(values, horiz=T, xlim=range(0:6),ylim=range(0:3), las=1)
which gives
The xaxs
parameter is used for the calculation of the x-axis (see ?par
).
Have a look at what it does
The default xaxs = "r"
hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue", breaks=b, xaxs="r")
par("usr")
#[1] -0.24 6.24 -1.00 26.00
The first two points give the x axis limits - you can see it has been expanded.
To force this to stay within the range of the data you can use the xaxs="i"
option
hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue", breaks=b, xaxs="i")
par("usr")
#[1] 0 6 -1 26
Which agrees with your barplot
barplot(values, horiz=T, xlim=range(0:6),ylim=range(0:3), las=1)
par("usr")
#[1] 0.00 6.00 -0.12 3.12
Upvotes: 3