r - 将bar的space和width参数打包以对齐2x1绘图窗口

标签 r plot bar-chart

我想在下面对齐底部的barplot,以使这些组在两个图之间垂直排列:

par(mfrow = c(2, 1))
n = 1:5
barplot(-2:2, width = n, space = .2)

barplot(matrix(-10:9, nrow = 4L, ncol = 5L), beside = TRUE,
        width = rep(n/4, each = 5L), space = c(0, .8))
Two bar plots stacked vertically. Each shows 5 "groups" of bars -- in the top plot, each "group" is just a single bar, but in the bottom plot, each group is 4 bars. Since these groups correspond, we might expect them to align vertically across the two plots, but this is not the case.
我一直盯着space(来自width)的barplot?barplot参数的定义,我确实希望上面的方法能起作用(但显然没有用):

width -- optional vector of bar widths. Re-cycled to length the number of bars drawn. Specifying a single value will have no visible effect...

space -- the amount of space (as a fraction of the average bar width) left before each bar. May be given as a single number or one number per bar. If height is a matrix and beside is TRUE, space may be specified by two numbers, where the first is the space between bars in the same group, and the second the space between the groups. If not given explicitly, it defaults to c(0,1) if height is a matrix and beside is TRUE, and to 0.2 otherwise.


在我阅读本文时,这意味着我们应该能够通过将每个组划分为4来匹配顶部图中的组宽度(因此n/4)。对于space,由于我们将每个小节的宽度除以4,因此平均宽度也将相同;因此,我们应该将分数乘以4以补偿此值(因此space = c(0, 4*.2))。
但是,这似乎被忽略了。实际上,似乎所有盒子都有相同的宽度!随意修改时,我只能使相对的组内宽度发生变化。
可以用barplot完成我的想法吗?如果没有,有人可以说例如ggplot2

最佳答案

也可以使用基本图执行此操作,但是它有助于将矩阵作为第二个图的向量传递。随后,您需要意识到space参数是平均钢筋宽度的一小部分。我这样做如下:

par(mfrow = c(2, 1))
widthsbarplot1 <- 1:5
spacesbarplot1 <- c(0, rep(.2, 4))

barplot(-2:2, width = widthsbarplot1, space = spacesbarplot1)

widthsbarplot2 <- rep(widthsbarplot1/4, each = 4)
spacesbetweengroupsbarplot2 <- mean(widthsbarplot2)

allspacesbarplot2 <- c(rep(0,4), rep(c(spacesbetweengroupsbarplot2, rep(0,3)), 4))

matrix2 <- matrix(-10:9, nrow = 4L, ncol = 5L)

barplot(c(matrix2),
    width = widthsbarplot2,
    space = allspacesbarplot2,
    col = c("red", "yellow", "green", "blue"))

Base plot

关于r - 将bar的space和width参数打包以对齐2x1绘图窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50147917/

相关文章:

r - 如何缩短heatmap.2()中ColSideColors的高度

r - 如何在分层热图树状图中添加聚类矩形

android - MPAndroidChart BarChart 在 Y 轴上显示限制

c# - MS 图表烛台 如何设置尾部颜色

使用 latex 中的条件颜色渲染表作为具有 rownames = TRUE 的 pdf 文档(rmarkdown、kable 和 kableExtra)

python - 多个交互式 matplotlib 在 python 2.7 和 3.6 中的行为不同

r - 无法使用 ggplot2 绘制多线图

r - ggplot多分组栏

r - 创建一个函数以将一个 data.frame 中的 NA 替换为另一个 data.frame 中的值

r - 用R中的重复键匹配两个数据帧