如何在堆栈条形图之间绘制线条?

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

我在两个配对的堆叠箱线图之间画线时遇到困难。我比较前后细胞组成的变化,尽管很难在图之间画线。下面显示的是我当前的脚本。我想将我的图(plot1)更改为如下所示的图(plot2) 非常感谢大家

data <- data.frame(
  Group = rep(c("Responder", "Non-responder"), each = 16), # 16 x 2 = 32
  Time = rep(c("Pre", "Post"), times = 16),               # 16 x 2 = 32
  CellType = rep(c("B", "Mono", "DC", "CD4_T", "CD8_T", "NK", "Other", "Platelet"), each = 2, times = 2), # 길이 32
  Proportion = runif(32, 0.01, 0.2)                       
)

data <- data %>%
  group_by(Group, Time) %>%
  mutate(Proportion = Proportion / sum(Proportion)) %>% 
  ungroup()

# Stacked Bar Plot 
ggplot(data, aes(x = Time, y = Proportion, fill = CellType)) +
  geom_bar(stat = "identity", position = "stack") + # Stacked bar plot
  facet_wrap(~ Group, ncol = 2) +                 
  scale_fill_brewer(palette = "Paired") +         
  theme_minimal() +                                
  labs(
    title = "Cell Type Proportions Before and After Treatment",
    x = "Time",
    y = "Cell Proportions",
    fill = "Cell Type"
  )

Plot1,我的箱线图 Plot2,我想让我的情节像这样

我通过谷歌和堆栈溢出搜索并找到了一些例子,虽然我还是新手,,,很难将这些代码实现到我的代码中,对不起大家..请帮助我

r ggplot2 geom-bar
1个回答
0
投票

我将如何解决这个问题:将时间作为一个因子,这样您就可以将其用作数字来定位 x 上的线。然后使用条件来决定它们是否应该从栏的右侧或左侧开始。

library(tidyverse)

data <- data.frame(
  Group = rep(c("Responder", "Non-responder"), each = 16), # 16 x 2 = 32
  Time = rep(c("Pre", "Post"), times = 16),               # 16 x 2 = 32
  CellType = rep(c("B", "Mono", "DC", "CD4_T", "CD8_T", "NK", "Other", "Platelet"), each = 2, times = 2), # 길이 32
  Proportion = runif(32, 0.01, 0.2)                       
)

data %>%
  group_by(Group, Time) %>%
  mutate(
    Proportion = Proportion / sum(Proportion), 
    Time = factor(Time)
    ) %>%
  ungroup() %>% 
  ggplot(
    aes(x = Time, y = Proportion, fill = CellType)) +
  geom_bar(stat = "identity", position = "stack", width = .5) + # Stacked bar plot
  facet_wrap(~ Group, ncol = 2) +                 
  scale_fill_brewer(palette = "Paired") +         
  theme_minimal() +                                
  labs(
    title = "Cell Type Proportions Before and After Treatment",
    x = "Time",
    y = "Cell Proportions",
    fill = "Cell Type"
  ) + 
  geom_line(
    aes(
      x = ifelse (Time == "Post", as.numeric(Time)+0.25, as.numeric(Time)-.25), 
      y = Proportion, 
      group = CellType), 
  position = position_stack(), 
  linetype = "dotted")
© www.soinside.com 2019 - 2024. All rights reserved.