我正在尝试找到一个如何堆叠2个图表的解决方案。一个图表显示数据计数,而第二个图表显示百分比。
这是启发我的帖子: Stacke different plots in a facet manner
目前,我创建了两个独立的图表:
set.seed(1)
trial.id <- sample(1:6, 1000, replace = TRUE, c(".35", ".25", ".2", ".15", ".04", ".01"))
surv <- sample(0:1, 1000, replace = TRUE)
trial.df <- data.frame(cbind(trial.id, surv))
# chart with counts information
windows(height = 800, width = 1500)
plotEX1 <- ggplot(trial.df, aes(x = as.factor(trial.id) , fill = as.factor(surv))) +
geom_bar(stat = "bin") +
ggtitle("Surival by Trial\n") +
labs(x = "\nTrial", y = "Patients (#)\n") +
scale_fill_discrete(name = "Survival")
plotEX1
# chart with % information
windows(height = 800, width = 1500)
plotEX2 <- ggplot(trial.df, aes(x = as.factor(trial.id) , fill = as.factor(surv))) +
geom_bar(stat = "bin", position = "fill") +
ggtitle("Surival by Trial\n") +
labs(x = "\nTrial", y = "Patients (%)\n") +
scale_fill_discrete(name = "Survival")
plotEX2
trial.id表示试运行次数。 surv代表试验成功的次数。
plotEX1显示了运行试验的次数以及成功率。 plotEX2是相同的东西,但显示为百分比。
目标是将这两个图表放在一起,因此读者很容易看到试验的重要性以及成功的百分比。
我认为让我失望的是试图融化数据。我尝试了几件事,但似乎无法让它发挥作用。任何帮助我指向正确方向的人都将不胜感激!
谢谢!
答案 0 :(得分:3)
根据我们的评论,我可能会做这样的事情:
new_dat <- melt(list(trial.df,trial.df),id.vars = 1:2)
new_dat$trial.id <- factor(new_dat$trial.id)
new_dat$surv <- factor(new_dat$surv)
ggplot() +
facet_wrap(~L1,nrow = 2,scales = "free_y") +
geom_bar(data = subset(new_dat,L1 == 1),
aes(x = trial.id , fill = surv),
stat = "bin",
position = "fill") +
geom_bar(data = subset(new_dat,L1 == 2),
aes(x = trial.id , fill = surv),
stat = "bin") +
ggtitle("Surival by Trial\n") +
labs(x = "\nTrial", y = "Patients (%)\n") +
scale_fill_discrete(name = "Survival")
(并忽略警告。)