我正在尝试创建一个带有格子的条形图,它有两个分组。第一个分组是堆叠的,而第二个分组不是。例如:
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)条组。每组酒吧都有一个“true”栏和一个“false”栏。我还要补充的是e的堆积值,这样每个“真”栏将分为三个部分:底部一个用于“是”,然后是“否”,它们“可能是”和与“假”栏相同。
我意识到图表会非常复杂,但它是表示我所拥有的数据的最佳方式。在公式中添加e,如b + c + e不是一个选项,因为我已经有了一组图,我需要保持相同的格式,因为它们彼此相关。另一方面,每组中有6个条形将使可读性变得更加困难。
谢谢!
答案 0 :(得分:1)
ggplot2
对您来说并不是一项艰难的要求,那么 lattice
将相对轻松地完成工作。我冒昧地扩展了您的数据集,以便存在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))