【问题标题】:How to create a multi-dimensional barchart如何创建多维条形图
【发布时间】:2013-08-12 18:06:35
【问题描述】:

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

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"))

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

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

谢谢!

【问题讨论】:

  • 这给了我一个图,每个方面只有一个 d 值(即,真或假,而不是两者)。这是故意的吗?

标签: r lattice


【解决方案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))

【讨论】:

  • 我以前从未使用过 ggplot2,但这看起来确实是我需要的。非常感谢你! :)
  • ggplot2 有一点学习曲线,但如果你习惯了 lattice 应该不会太糟糕,而且我认为它最终会让很多任务变得更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2022-09-30
相关资源
最近更新 更多