首页 > 解决方案 > 堆积条形图

问题描述

我有一张表格,其中包含有关患者生存/复发的分类变量。

数据如下所示(约 500 行):

肿瘤类型 差异化 阶段 倍性 复发 死亡
子宫内膜样 G2 IA 二倍体 无复发 没有死亡
浆液 G1 国际文凭组织 非整倍体 复发 没有死亡

我的意图是画出类似的东西: 终极观点

我此时卡在某个地方:

#Importing the libraries
# Packages
library(ggplot2)
library(gridExtra)

#Drawing the plots

p1 <- ggplot(df, aes(Relapse, group = Stage)) +
geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
scale_y_continuous(labels=scales::percent) +
ylab("Relative frequencies") +
facet_grid(~Stage) +
labs(title = "Stage", tag = "A") +
theme(plot.title = element_text(hjust = 0.5),
plot.tag = element_text())

p2 <- ggplot(df, aes(Relapse, group = Ploidy)) +
geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
scale_y_continuous(labels=scales::percent) +
ylab("Relative frequencies") +
facet_grid(~Ploidy) +
labs(title = "Ploidy", tag = "B") +
theme(plot.title = element_text(hjust = 0.5),
plot.tag = element_text())

p3 <- ggplot(df, aes(Relapse, group = Differentiation)) +
  geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
  scale_y_continuous(labels=scales::percent) +
  ylab("Relative frequencies") +
  facet_grid(~Differentiation) +
  labs(title = "Differentiation", tag = "C") +
  theme(plot.title = element_text(hjust = 0.5),
        plot.tag = element_text())

p4 <- ggplot(df, aes(Relapse, group = Tumor_Type)) +
  geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
  scale_y_continuous(labels=scales::percent) +
  ylab("Relative frequencies") +
  facet_grid(~Tumor_Type) +
  labs(title = "Tumor_Type", tag = "D") +
  theme(plot.title = element_text(hjust = 0.5),
        plot.tag = element_text())

#Arranging them into one
grid.arrange(p1, p2, p3, p4)

它给我带来了以下情节: 结果图

所以问题是:

  1. 如何为“复发”制作百分比堆积条形图,并为“死亡”制作并排分隔,使它们具有相似的高度?
  2. 如示例图像所示,如何绘制单个图例?

标签: rggplot2

解决方案


推荐阅读