我的问题增加了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()
已弃用,所以我不打算将其包括在内。
我无法弄清楚如何设置min y,max y值来将条形设置在彼此之上(如果这是我应该去的路线)。简单地将position="dodge"
更改为position="stack"
只会使它们彼此重叠并且难以理解。如果有意义的话,我也希望仅将轮廓保持在所有值而不是“输入”和“输出”值。
答案 0 :(得分:2)
以下是使用通过融合函数重新整形的代码:
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")
)
plotData <- dat.agg[, c("category1", "outcome", "cat1.n", "yes")]
plotData <- melt(plotData, id.vars = c("category1", "outcome"))
plotData$FillColor <- ordered(paste0(plotData$category1, "_", plotData$variable), levels=c("in_cat1.n", "out_cat1.n", "in_yes", "out_yes")) # order it the way you want your values to be displayed on the plot
# Plot - outcome will be x for both layers
ggplot(plotData, aes(x = outcome)) +
# Add the layer
geom_bar(aes(weight = value, fill = FillColor)) +
# Add colors as per your desire
scale_fill_manual(values = c(alpha("#1F78B4", 1), alpha("#1F78B4", 0.5), alpha("#33A02C", 1), alpha("#33A02C", 0.5))) +
# Title
ggtitle("A pretty plot <3")