Ziv Ziv - 5 months ago 28
R Question

x-axis in barplot cannot align to other plots

I tried to combined three plot.hist didn't have

,so I use barplot.But when use same region to color barplot and point.It cannot align together.I tried set barplot range(
xlim = c(-3,3)
),but it just show a part of barplot. How can I set these plot in same x-axis range,color region can align to point plot's dashed lines.Here is my code:


def.par <- par(no.readonly = TRUE) # save default, for resetting...
x <- pmin(3, pmax(-3, rnorm(5000)))
y <- pmin(3, pmax(-3, rnorm(5000)))
xhist <- hist(x, breaks=1000, plot=FALSE)
yhist <- hist(y, breaks=1000, plot=FALSE)
cut1 <- cut(xhist$density, c(-Inf,-1.8,1.8,Inf))
cut2 <- cut(yhist$density, c(-Inf,-2.9,2.9,Inf))
top <- max(c(xhist$density, yhist$density))
xrange <- c(-3,3)
yrange <- c(-3,3)
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE)#layout.show(nf)ZSSS
plot(x, y, xlim=xrange, ylim=yrange, type="p",pch=".",cex=1,xlab="T1", ylab="T2",col="grey")


breaks <- c(-Inf, -2.5, 2.5, Inf)
col1 <- c("blue", "grey", "red")[findInterval(xhist$breaks, vec=breaks)]
barplot(xhist$density, axes=TRUE,ylab="T3",border=col1)

col2 <- c("grey", "red")[(yhist$breaks >= 0.5) + 1]
barplot(yhist$density, axes=TRUE, xlab="T4",space=0, horiz=TRUE,border=col2)



2nd par(mar=c(bottom, left, up, right)) needs the same left and right margins as plot(), so when margin of plot() is c(3,3,0,0), it is par(mar=c(0,3,1,0)). 3rd needs the same bottom and up margins, so it is par(mar=c(3,0,0,1)).

[response to the comment]
The reason is clear. Default params of mgp = c(axis_title, axis_label, axis_line) is c(3, 1, 0). It means axis titles is written on margin 3-4, so when mar = c(3, 3, 0, 0) axis title is outside of a graph. You can solve it by increasing mar and/or decreasing mgp.

I feel the combination makes a cool graph, such as;

par(mar=c(3.5, 3.5, 0, 0), mgp = c(2.5, 1, 0)) # for plot()
par(mar=c(0, 3.5, 1, 1), mgp=c(2.5, 1, 0))     # for 1st barplot()
par(mar=c(3.5, 0, 1, 1), mgp = c(2.5, 1, 0))   # for 2nd barplot()