You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为药物响应/无响应患者的细胞类型数据绘制有序条形图?

问题描述

现有一组记录药物响应患者与无响应患者中各类细胞类型出现情况的数据集,其R语言dput输出如下:

cellsdata <- structure(list(response = c(1, 7, 2, 3, 4, 2, 1, 2, 1, 5, 5, 
4, 2, 0, 0, 2, 0, 0, 1, 3, 1, 2, 1, 0, 4, 3, 2, 3, 1, 1, 5, 0, 
2, 2, 5, 4, 4, 2), no_response = c(1, 0, 0, 0, 0, 0, 1, 0, 1, 
0, 0, 0, 0, 3, 2, 3, 2, 0, 3, 0, 0, 0, 1, 1, 0, 1, 4, 0, 0, 0, 
0, 2, 1, 0, 0, 0, 0, 0)), class = "data.frame", row.names = c("Adipocytes", 
"B-cells", "Basophils", "CD4+ memory T-cells", "CD4+ naive T-cells", 
"CD4+ T-cells", "CD4+ Tcm", "CD4+ Tem", "CD8+ naive T-cells", 
"CD8+ T-cells", "CD8+ Tcm", "Class-switched memory B-cells", 
"DC", "Endothelial cells", "Eosinophils", "Epithelial cells", 
"Fibroblasts", "Hepatocytes", "ly Endothelial cells", "Macrophages", 
"Macrophages M1", "Macrophages M2", "Mast cells", "Melanocytes", 
"Memory B-cells", "Monocytes", "mv Endothelial cells", "naive B-cells", 
"Neutrophils", "NK cells", "pDC", "Pericytes", "Plasma cells", 
"pro B-cells", "Tgd cells", "Th1 cells", "Th2 cells", "Tregs"
))

需要绘制分组条形图(每个细胞类型对应两个条形,分别代表响应/无响应患者),且按响应患者的数值从高到低从左至右排序。

实现步骤(R语言)

使用tidyverse包完成数据处理与绘图:

  1. 加载依赖包
library(tidyverse)
  1. 数据预处理
    将行名转为细胞类型列,转换为长格式,并按响应患者的数值对细胞类型排序:
cells_tidy <- cellsdata %>%
  rownames_to_column(var = "cell_type") %>%  # 把行名转为cell_type列
  pivot_longer(cols = c(response, no_response), 
               names_to = "patient_group", 
               values_to = "count") %>%  # 转换为长格式,方便分组绘图
  mutate(cell_type = fct_reorder(cell_type, 
                                 count[patient_group == "response"], 
                                 .desc = TRUE))  # 按响应组的数值降序排序细胞类型
  1. 绘制分组条形图
ggplot(cells_tidy, aes(x = cell_type, y = count, fill = patient_group)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +  # 设置分组条形间距与宽度
  scale_fill_manual(values = c("response" = "#1f77b4", "no_response" = "#ff7f0e")) +  # 自定义分组颜色
  labs(title = "细胞类型在药物响应/无响应患者中的分布",
       x = "细胞类型",
       y = "出现次数",
       fill = "患者分组") +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # 旋转x轴标签,避免名称重叠
说明
  • 排序逻辑:以响应患者的细胞数值为依据,从左到右按降序排列
  • position_dodge参数用于避免分组条形重叠,提升可读性
  • 旋转x轴标签是为了解决细胞类型名称过长导致的显示问题

内容的提问来源于stack exchange,提问作者Programming Noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 12:31:03