【发布时间】:2016-03-29 23:56:03
【问题描述】:
我的问题添加到 4 年前提交的答案here。用户创建了闪避堆叠条形图,我想知道如何/是否可以为每个“结果”级别将这些闪避设置在彼此之上。
这是用户的答案和代码:
library(ggplot2)
library(plyr)
N <- 50*(2*8*2)
outcome <- sample(ordered(seq(8)),N,replace=TRUE,prob=c(seq(4)/20,rev(seq(4)/20)) )
category2 <- ifelse( outcome==1, sample(c("yes","not"), prob=c(.95,.05)), sample(c("yes","not"), prob=c(.35,.65)) )
dat <- data.frame(
category1=rep(c("in","out"),each=N/2),
category2=category2,
outcome=outcome
)
# Aggregate
dat.agg <- ddply(dat, .var = c("category1", "outcome"), .fun = summarise,
cat1.n = length(outcome),
yes = sum(category2 %in% "yes"),
not = sum(category2 %in% "not")
)
# Plot - outcome will be x for both layers
ggplot(dat.agg, aes(x = outcome)) +
# First layer of bars - for category1 totals by outcome
geom_bar(aes(weight = cat1.n, fill = category1), position = "dodge") +
# Second layer of bars - number of "yes" by outcome and category1
geom_bar(aes(weight = yes, fill = category1), position = "dodge") +
# Transparency to make total lighter than "yes" - I am bad at colors
scale_fill_manual(value = c(alpha("#1F78B4", 0.5), alpha("#33A02C", 0.5))) +
# Title
opts(title = "A pretty plot <3")
这是我正在尝试的非常粗糙的 MS Paint 绘图:
我知道opts() 已被弃用,所以我不包括以后的内容。
我不知道如何设置最小 y、最大 y 值以将条设置在彼此之上(如果这甚至是我应该走的路线)。只需将position="dodge" 更改为position="stack" 只会使它们相互重叠且难以理解。如果有意义的话,我也希望只在 ALL 值周围保留大纲,而不是在“in”和“out”值周围。
【问题讨论】:
-
我想澄清一些事情。如果您查看
dat.agg的值,就在outcome = 1和category = in的位置,条形的高度是47,但“in”和“out”的总高度是73。我怀疑你想要堆叠酒吧高度是两者的总和,这是正确的吗?无论哪种方式,您都可能希望使用tidyr:dat.agg.deep <- dat.agg %>% select(-not) %>% gather(val_type, val, -category1, -outcome)来重塑您的数据以执行您想要的操作。not列被删除,因为您没有绘制它。然后你会绘制dat.agg.deep。