同一图表中的多个条形图保持相同的轴和相同的条宽

时间:2013-09-22 06:49:19

标签: r axes par bar-chart

非常愚蠢的问题,但我无法在网上找到答案:

需要像这样绘制多个条形图:

 i=1:4
 main = paste ("Location ", i)

 windows()
 par(mfrow=c(2,2))
 a<-table(c(rep(10, 6), rep(4, 32)))
 b<-table(c(rep(9, 6), rep(10, 32), rep(11,4)))
 c<-table(c(rep(10, 6)))
 d<-table(c(rep(10, 3), rep(9, 3), rep(8, 5)))

 barplot(a,  main=main[1], xlab='RSSI')
 barplot(b,  main=main[2], xlab='RSSI')
 barplot(c,  main=main[3], xlab='RSSI')#, width=0.5
 barplot(d,  main=main[4], xlab='RSSI')

1)是否可以保持轴刻度不变,以便在每个图形上都相同?

2)是否可以在图表中保持条宽度不变?我尝试了宽度,但它似乎不起作用,我想让它保持不变并固定在图形之间。

由于

编辑:for 2)我知道你可以添加零,所以所有图形都涉及相同数量的类,但由于我正在绘制一个for循环,我已经删除以使示例更简单,我宁愿如果可能的话,用另一种方法来做。 再次感谢

2 个答案:

答案 0 :(得分:1)

可能只是为了您的示例,您将每个绘图的数据保存在单独的向量中。无论如何,如果位置数量会大得多,您很快就会让工作空间变得杂乱无章,而且您需要多次拨打tablebarplot

使用base R函数或ggplot进行绘图时,使用数据框中存储的数据会更容易。此外,如果在每个图中使用每个位置的相同类别集,即包括零计数的RSSI类,则可以更容易地比较不同位置中不同级别的RSSI的计数。您也可以跨位置使用相同的y轴比例。以下是ggplot

的小例子
library(ggplot2)

# create a data frame with the data in your vectors
# 'x' is the value, and 'loc' the location of each registration
df <- data.frame(x = c(rep(10, 6), rep(4, 32),
                       rep(9, 6), rep(10, 32), rep(11, 4),
                       rep(10, 6),
                       rep(10, 3), rep(9, 3), rep(8, 5)),
                 loc = c(rep("a", 6+32), rep("b", 6+32+4), rep("c", 6), rep("d", 3+3+5)))

# plot using geom_bar, which default counts the cases for each level of  - no need for 'table'
ggplot(data = df, aes(x = factor(x))) +
  geom_bar() +
  facet_wrap(~ loc)

enter image description here

答案 1 :(得分:0)

查看xlim中描述的ylim?barplot参数:

barplot(a,  main=main[1], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))
barplot(b,  main=main[2], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))
barplot(c,  main=main[3], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))
barplot(d,  main=main[4], xlab='RSSI', xlim=c(0, 4), ylim=c(0, 32))

enter image description here

xlimwidth相互影响。)