在条形图中精细控制条宽

时间:2014-11-03 02:42:33

标签: r plot width bar-chart

我想在同一个图中合并4个数字。每个barplot都与image图有关。我希望条形宽度与image图中的网格宽度完全相同。上方条形图和左侧条形图。

我已粘贴我的代码。我怎样才能为此目的进行修改?或者我可以使用ggplot2吗?

datMat <- matrix(rep(1, 100), nrow=10)
op=par(oma=c(1, 1, 1, 1), mar=c(1, 1, 1, 1), lwd=0.2, cex=.5)

nf <- layout(matrix(c(0, 1, 0, 2, 3, 4), 2, 3, byrow=TRUE), widths=c(1, 6, 1),
             heights=c(1, 3), respect=TRUE)

par(mar=c(3, 0.5, 3, 0), mgp=c(0, 1, -2.2))
barplot(seq(1, 10), width=1, xlim=c(0, ncol(datMat)), xlab="", space=0, 
        col="blue", border="white" )

box("inner", lty="dotted", col="green")
box("outer", lty="solid", col="green")

par(mar=c(0, 0, 0, 0), mgp=c(0, 1, -1))
barplot(-seq(1, 10), ylim=c(0, nrow(datMat)), width=1.025, horiz=TRUE, ,axes
       =T, space=0, col="blue", border="white" )

par(mar=c(1, 0, 0, 0))
x.len <- ncol(datMat)
y.len <- nrow(datMat)
single.col <- 'chartreuse4'
double.col <- 'blue4'
triple.col <- '#FFFF33'
four.col <- '#FF7F00'
five.col <- '#E41A1C'
colors <- c('grey90', single.col, double.col, triple.col, four.col, five.col)

image(x=1:x.len, y=1:y.len, z=t(datMat), col=colors, 
      breaks=c(-0.5, 0.5 , 1.5 , 2.5 , 3.5 , 4.5 , 5.5), axes=FALSE, ann=F)
abline(h=seq(0.5, 0.5+y.len), col='white', lwd=0.5);
abline(v=seq(0.5, 0.5+x.len), col='white', lwd=0.5)

par(mar=c(0, 0, 0, 0), mgp=c(0, 1, 0))
barplot(seq(1, 10), ylim=c(0, nrow(datMat)), width=.5, horiz=TRUE, axes=FALSE, 
        space=0, col="blue", border ="white" )
axis(side=1)


sessionInfo()    
# R version 3.1.1 (2014-07-10)   
# Platform: x86_64-apple-darwin13.1.0 (64-bit)
# 
# locale:
# [1] C/UTF-8/C/C/C/C
# 
# attached base packages:
# [1] datasets  utils     stats     graphics  grDevices methods   base
# 
# other attached packages:
# [1] xlsx_0.5.7                  xlsxjars_0.6.1
# [3] rJava_0.9-6                 nutshell_2.0
# [5] nutshell.audioscrobbler_1.0 nutshell.bbdb_1.0
# [7] faraway_1.0.6               MASS_7.3-35
# 
# loaded via a namespace (and not attached):
# [1] tools_3.1.1

1 个答案:

答案 0 :(得分:1)

如果您未指定xlimylim,则图表将填充可用空间。然后,只需为上图提供xaxs='i',为左图和右图提供yaxs='i'

par(oma=c(1, 1, 1, 1), mar=c(1, 1, 1, 1), lwd=0.2, cex=0.5)

nf <- layout(matrix(c(0, 2, 0, 3, 1, 4), 2, 3, byrow=TRUE), 
             widths=c(1, 6, 1), heights=c(1, 3), respect=TRUE)

par(mar=rep(0, 4))
m <- matrix(runif(100), ncol=10)
image(x=seq_len(ncol(m)), y=seq_len(nrow(m)), z=t(m), axes=FALSE, ann=F)   
abline(h=seq(0.5, 0.5 + nrow(m)), v=seq(0.5, 0.5 + ncol(m)), col="white")

par(mar=c(1, 0, 0, 0))
barplot(seq(1, 10), xlab="", space=0, border="white", xaxs='i')
par(mar=c(0, 0, 0, 1))
barplot(-seq(1, 10), horiz=TRUE, space=0, border="white", yaxs='i', xaxt='n')
axis(1, at=axTicks(1), labels=-axTicks(1)) # correct x-axis tick labels for left plot
par(mar=c(0, 1, 0, 0))
barplot(seq(1, 10), horiz=TRUE, axes=F, space=0, border="white", yaxs='i')
axis(1)

enter image description here