gpt4 book ai didi

r - 在同一图中交错和堆叠 geom_bar?

转载 作者:行者123 更新时间:2023-12-04 14:32:51 26 4
gpt4 key购买 nike

我有下图,它本质上是两个分布的直方图,它们并排绘制:

my.barplot <- function( df, title="", ... ) {
df.count <- aggregate( df$outcome, by=list(df$category1,df$outcome), FUN=length )
colnames( df.count ) <- c("category1","outcome","n")
df.total <- aggregate( df.count$n, by=list(df.count$category1), FUN=sum )
colnames( df.total ) <- c("category1","total")
df.dens <- merge(df.count, df.total)
df.dens$dens <- with( df.dens, n/total )
p <- ggplot( df.dens, aes( x=outcome, fill=category1 ), ... )
p <- p + geom_bar( aes( y=dens ), position="dodge" )
p <- p + opts( axis.text.x=theme_text(angle=-90,hjust=0), title=title )
p
}

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
)

my.barplot(dat)

existing barchart

我想在每个条形图中绘制属于某个第二类的比例。如果不需要按第一类组织它,我只会堆叠条形。但是,我无法弄清楚如何按第二个类别进行堆叠。基本上在每个结果类别 1 条中,我希望类别 2 中的比例具有更深的阴影。

这是我正在尝试创建的 GIMP 图像:

barchart with stacked proportions of category2

最佳答案

基本图形?!?永不出错

这是我想出的。我承认我很难理解你所有的聚合和准备,所以我只是聚合到计数,可能都弄错了 - 但似乎你处于一个位置,从一个功能性的情节开始可能更容易,并且然后正确输入。这行得通吗?

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

Plot with bars that are simultaneously dodged, overlaid, and transparent

关于r - 在同一图中交错和堆叠 geom_bar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9493159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com