【问题标题】:Specify spaces between bars in barplot在条形图中指定条形之间的空间
【发布时间】:2023-04-04 22:22:02
【问题描述】:

我正在尝试使用 R 生成一个条形图,其中条形的宽度不同,它们之间的空间也不同。例如我有一个矩阵

data <- matrix(c(1,2,2,4,7,1,11,12,3), ncol = 3, byrow = T)
colnames(data) <- c("Start", "Stop", "Height")

我想生成一个像这样的图(对不起草图):

|                                 __ 
|   __                           |  |
|  |  |      ________            |  |
|  |  |     |        |           |  |
------------------- ------------------
0  1  2  3  4  5  6  7  8  9  10 11 12

据我了解, barplot() 允许您指定宽度,但条形之间的空间只能表示为平均条形宽度的一小部分。但是,我想为条形之间的空格指定特定的(整数)数字。 我会很感激任何提示/想法!

【问题讨论】:

  • +1 精彩剧情! :)

标签: r plot


【解决方案1】:

获得所需内容的一种方法是创建虚拟的空条。例如,

##h specifies the heights
##Dummy bars have zero heights
h = c(0, 2, 0, 1, 0, 3)
w = c(1, 1, 2, 3, 4, 1)

然后使用barplot进行绘图

##For the dummy bars, remove the border
##Also set the space=0 to get the correct axis
barplot(h, width=w, border=c(NA, "black"), space=0)
axis(1, 0:14)

【讨论】:

    【解决方案2】:

    如果您将space 参数除以mean(Width),您也可以得到:

    data <- as.data.frame(data)
    data$Width <- with(data, Stop - Start)
    data$Space <- with(data, Start - c(0,head(Stop,-1)))
    with(data, barplot(Height, Width, space=Space/mean(Width), xlim=c(0,13) ) )
    axis(1,0:14)
    

    【讨论】: