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

请求绘制癌症类型在train_set与test_set的并列柱状图

绘制癌症类型训练集与测试集样本量的并列柱状图

给定数据集

以下是8类癌症在训练集和测试集中的样本数量分布:

癌症类型训练集样本数测试集样本数
乳腺癌110
结直肠癌42
黑色素瘤321108
肺癌2813
肾细胞癌527174
肉瘤50
胸腺癌55
膀胱癌24277

实现代码(R语言)

使用ggplot2和tidyr包可以快速绘制符合要求的并列柱状图,步骤如下:

1. 导入并整理数据

# 创建数据集
cancer_data <- data.frame(
  癌症类型 = c("乳腺癌", "结直肠癌", "黑色素瘤", "肺癌", "肾细胞癌", "肉瘤", "胸腺癌", "膀胱癌"),
  训练集 = c(11, 4, 321, 28, 527, 5, 5, 242),
  测试集 = c(0, 2, 108, 13, 174, 0, 5, 77)
)

# 加载tidyr包,转换为长格式数据
library(tidyr)
cancer_long <- pivot_longer(cancer_data, cols = c("训练集", "测试集"), 
                            names_to = "数据集类型", values_to = "样本数量")

2. 绘制并列柱状图

# 加载ggplot2包
library(ggplot2)

# 生成可视化图表
ggplot(cancer_long, aes(x = 癌症类型, y = 样本数量, fill = 数据集类型)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  geom_text(aes(label = 样本数量), position = position_dodge(width = 0.8), 
            vjust = -0.5, size = 3) +
  labs(title = "各类型癌症训练集与测试集样本量对比",
       x = "癌症类型",
       y = "样本数量",
       fill = "数据集类型") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_fill_manual(values = c("#1f77b4", "#ff7f0e"))

代码说明

  • position_dodge(width = 0.8):实现训练集与测试集柱子的并列排布
  • geom_text:在每个柱子顶部添加样本数量标签,便于直观读取数值
  • theme(axis.text.x = ...):旋转x轴标签,避免长名称重叠
  • scale_fill_manual:自定义柱子填充色,可根据需求调整

内容的提问来源于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 15:10:19