【问题标题】:x-axis in barplot cannot align to other plotsbarplot 中的 x 轴无法与其他图对齐
【发布时间】:2017-03-31 11:58:37
【问题描述】:

我尝试合并三个 plot.hist 没有horizal,所以我使用 barplot。但是当使用相同区域为 barplot 和点着色时。它无法对齐。我尝试设置 barplot 范围(xlim = c(-3,3)) ,但它只显示条形图的一部分。如何将这些绘图设置在相同的 x 轴范围内,颜色区域可以与点绘图的虚线对齐。这是我的代码:

```

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
par(mar=c(3,3,0,0))
plot(x, y, xlim=xrange, ylim=yrange, type="p",pch=".",cex=1,xlab="T1", ylab="T2",col="grey")
abline(h=0.5,lty=2,lwd=1.5,col="black")
abline(v=-2.5,lty=2,lwd=1.5,col="black")
abline(v=2.5,lty=2,lwd=1.5,col="black")

par(mar=c(0,3,1,1))

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)

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

```

【问题讨论】:

    标签: r plot histogram bar-chart axis


    【解决方案1】:

    第二个par(mar=c(bottom, left, up, right))需要和plot()一样的左右边距,所以当plot()的边距是c(3,3,0,0)时,它就是par(mar=c(0,3,1,0))。第三个需要相同的下边距和上边距,所以它是par(mar=c(3,0,0,1))

    [回复评论]
    mgp = c(axis_title, axis_label, axis_line) 的默认参数是 c(3, 1, 0)。这意味着轴标题写在边距 3-4 上,所以当mar = c(3, 3, 0, 0) 时,轴标题在图表之外。您可以通过增加mar 和/或减少mgp 来解决它。

    我觉得这种组合形成了一个很酷的图表,例如;

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

    【讨论】:

    • 谢谢!对了,我发现了一个新问题。我所有的 x 轴和 y 轴实验室都没有显示在图中。你知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2017-05-20
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多