1

我正在尝试用格子创建一个条形图,它有两个分组。第一个分组是堆叠的,而第二个不是。例如:

a <- factor(rep(c(1,2), times = 6))
b <- factor(rep(c(1,2,3), times = 4))
c <- factor(rep(c(1,2,3,4), times = 3))
d <- factor(rep(c("true", "false"), each = 6))
e <- factor(rep(c("yes", "no", "may be"), each = 4))
value <- c(5,8,2,4,1,8,9,3,5,6,3,12)

目前我正在做以下事情:

a <- factor(rep(c(1,2), times = 6))
b <- factor(rep(c(1,2,3), times = 4))
c <- factor(rep(c(1,2,3,4), times = 3))
d <- factor(rep(c("true", "false"), each = 6))
e <- factor(rep(c("yes", "no", "may be"), each = 4))
value <- c(5,8,2,4,1,8,9,3,5,6,3,12)

barchart(value ~ a | b + c, 
       groups = d, stack = FALSE, 
       auto.key=TRUE,
       scales = list(x = "free"))

这导致长度(b)*长度(c)组条形图,每个都有长度(a)组条形图。每组条形都有一个“真”条和一个“假”条。我还想添加的是 e 的堆叠值,这样每个“真实”条将分为三个部分:底部的一个将是“是”,然后是“否”,它们是“可能是”和与“假”栏相同。

我意识到图表会非常复杂,但它是表示我拥有的数据的最佳方式。在公式中添加 e,如 b + c + e 不是一个选项,因为我已经有一组图,我需要保持相同的格式,因为它们彼此相关。另一方面,每组有 6 个小节会使可读性变得更加困难。

谢谢!

4

1 回答 1

1

ggplot2lattice如果使用对您来说不是一个硬性要求,那么将相对容易地完成这项工作。我冒昧地扩展了您的数据集,以便出现 a、b、c、d 和 e 的所有组合。

# Load required packages
require(ggplot2)
require(plyr)

# Make factors with the same levels as in the original post
#   but 100x longer, and in random order so all combinations are present
a <- sample(factor(rep(c(1,2), times = 600)))
b <- sample(factor(rep(c(1,2,3), times = 400)))
c <- sample(factor(rep(c(1,2,3,4), times = 300)))
d <- sample(factor(rep(c("true", "false"), each = 600)))
e <- sample(factor(rep(c("yes", "no", "may be"), each = 400)))
value <- runif(1200)

# Put them in a data frame
df <- data.frame(a=a, b=b, c=c, d=d, e=e, value=value)

# Calculate the sum of the value columns for each unique combination of a, b, c, d, and e
#   I think this is what you'd like - am not totally sure
ds <- ddply(df, c("a", "b", "c", "d", "e"), summarise, sum.value=sum(value, na.omit=TRUE))

# Make the plot
ggplot(ds, aes(x=d, y=sum.value, fill=e)) + geom_bar(stat="identity") +
  facet_grid(a~b+c) +
  theme(axis.text.x=element_text(angle=-90))

在此处输入图像描述

于 2013-08-12T19:02:57.650 回答