如何将分类变量添加到百分比堆积条形图中?

问题描述 投票:0回答:1

第一次在这里发帖,所以如果我遗漏了任何通常包含的细节,请告诉我。 我正在使用 ggplot2 和 ggdendro 制作一个带有分层聚类树的堆叠条形百分比图,其中每个节点都与我的一个条形图相关联。

1

正如你所看到的,我或多或少已经弄清楚了这一点(注意这只是我数据的一个子集。我现在想要将一个分类变量与每个条形图关联起来,其中每个变量将由一种颜色表示(在我的例子中)这是 HIV+ 或 HIV-,每个条代表给定类别中细胞的百分比)。此外,我想弄清楚如何将样本名称添加到每个树状图节点,但这个问题不太紧迫。 下面是我正在使用的代码块。

library(ggplot2)
library(ggdendro)

# Load in phenograph data
TotalPercentage <- read.csv("~/TotalPercentage.csv", header=TRUE)

#generate tree
tree <- hclust(dist(TotalPercentage))
tree <- dendro_data(tree)

data <- cbind(TotalPercentage, x = match(rownames(TotalPercentage), tree$labels$label))



# plot below stacked bar, in "data = tidyr::pivot_longer(data, c(2..." include
## all columns (clusters) but exclude colun 1 as this value is our sample ID

scale <- .5
p <- ggplot() +
  geom_col(
    data = tidyr::pivot_longer(data, c(2, 3 , 4, 5, 6, 7, 8)),
    aes(x = x,
        y = value, fill = factor(name)),
  ) +
  labs(title="Unsupervised Clustering of Phenograph Output",
          x ="Cluster Representation (%)", y = "Participant Sample"
  ) +
  geom_segment(
    data = tree$segments,
    aes(x = x, y = -y * scale, xend = xend, yend = -yend * scale)
  )

p

为了简单起见,这是一个行数较少的示例数据集

data.frame(
  `Participant ID` = c("123", "456", "789"),
  `1` = c(.1933, .1721, 34.26),
  `2` = c(20.95, 4.97, 2.212),
  `3` = c(11.31, 35.34, .027),
  `4` = c(35.55, 15.03, 0),
  `5` = c(.26, .87, 7.58),
  `6` = c(12.85, 33.44, .033),
  `7` = c(2.04, 3.77, 4.32)
)

患者 1 和患者 3 患有 HIV,但患者 2 的 HIV 呈阴性

最后这是我最终想要制作的一个例子

(https://i.stack.imgur.com/uAWxR.png)

我已经到处寻找如何做到这一点,但我是 R 新手,所以我有点自由浮动,不知道下一步该做什么。预先感谢您的帮助。

r ggplot2 bioinformatics categorical-data ggdendro
1个回答
0
投票

像这样,随机生成数据:

# randomly generated phenograph data
set.seed(1)
TotalPercentage <- data.frame(
  `Participant ID` = c("123", "456", "789"),
  `1` = 125*runif(72),
  `2` = 75*runif(72),
  `3` = 175*runif(72),
  `4` = 10*runif(72),
  `5` = 100*runif(72),
  `6` = 150*runif(72),
  `7` = 200*runif(72)
)

现在聚类、标准化并绘图:

tree <- hclust(dist(TotalPercentage))
tree <- dendro_data(tree)
data <- cbind(TotalPercentage, x = match(rownames(TotalPercentage), tree$labels$label))
data[,2:8] <- 100*data[,2:8] / rowSums(data[,2:8]) # row-normalize
scale <- .05
ggplot() +
  geom_col(
    data = tidyr::pivot_longer(data, c(2, 3 , 4, 5, 6, 7, 8)),
    aes(x = x,
        y = value, fill = factor(name)),
  ) +
  labs(title="Unsupervised Clustering of Phenograph Output",
       x ="Cluster Representation (%)", y = "Participant Sample"
  ) +
  geom_segment(
    data = tree$segments,
    aes(x = x, y = -y * scale, xend = xend, yend = -yend * scale)
  )

© www.soinside.com 2019 - 2024. All rights reserved.