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

在R中绘制含Response与No_Response双变量的分组条形图

绘制细胞类型分组条形图(响应/无响应对比)

步骤1:加载依赖包并导入数据

# 加载所需工具包
library(ggplot2)
library(tidyr)

# 导入你的细胞数据框
cell_data <- structure(list(cells = 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"), Response = c(0, 8, 0, 5, 4, 4, 3, 3, 2, 3, 8, 5, 3, 
0, 1, 1, 0, 2, 1, 5, 3, 3, 2, 2, 7, 4, 3, 5, 2, 2, 8, 0, 1, 2, 
3, 3, 2, 8), No_Response = c(6, 0, 1, 1, 2, 2, 1, 3, 3, 1, 1, 
2, 1, 2, 3, 5, 2, 2, 3, 1, 1, 2, 2, 1, 0, 0, 5, 0, 1, 0, 0, 3, 
1, 1, 5, 3, 1, 3)), class = "data.frame", row.names = c(NA, -38L
))

步骤2:转换数据格式

ggplot更适合处理长格式数据,需要把原数据的宽格式转换为长格式:

cell_data_long <- pivot_longer(cell_data, 
                               cols = c(Response, No_Response), 
                               names_to = "Group", 
                               values_to = "Value")

步骤3:绘制分组条形图

按要求设置颜色,同时优化x轴标签避免重叠:

ggplot(cell_data_long, aes(x = cells, y = Value, fill = Group)) +
  # 绘制分组条形,设置间距避免重叠
  geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) +
  # 指定Response为蓝色,No_Response为红色
  scale_fill_manual(values = c("Response" = "#0066CC", "No_Response" = "#CC3300")) +
  # 旋转x轴标签,解决名称过长重叠问题
  theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8)) +
  # 设置坐标轴和标题
  labs(x = "细胞类型", y = "数值", title = "细胞响应/无响应分组对比") +
  # 让标题居中显示
  theme(plot.title = element_text(hjust = 0.5))

关键参数说明

  • position_dodge(width = 0.8):保证分组条形并排展示,不会重叠
  • scale_fill_manual:完全自定义分组颜色,可替换为任意十六进制颜色码
  • axis.text.x:调整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.20 10:54:51