R使用ggplot实现基础数据可视化

  1. 在开始之前,我们需要设置工作目录并导入数据集 liver.df 作为案例示范,如果需要liver.df可以评论。
R 复制代码
# set your own working directory!
setwd("liver_files_location")

liver.cells.df <- read.table("liver.cells.txt", header = FALSE)
liver.section.df <- read.table("liver.section.txt", header = FALSE)
liver.exper.df <- read.table("liver.exper.txt", header = FALSE) 
liver.gt.df <- read.table("liver.gt.txt", header = TRUE)
liver.df <- data.frame(liver.cells.df, liver.section.df, liver.exper.df, liver.gt.df)
colnames(liver.df) <- c("cells", "section", "exper", colnames(liver.gt.df))
  1. 安装ggplot包。
R 复制代码
install.packages("ggplot2")
library(ggplot2)

ggplot2 是由 Hadley Wickham 创建的 R 包。它提供了一个强大的图形工具,用于创建美观且复杂的图表。近年来,它在 R 社区中的受欢迎程度急剧上升。该包允许您以直接的方式创建图表,展示单变量和多变量的数值和分类数据。分组可以通过颜色、符号、大小和透明度来表示。

  1. 散点图绘制:
R 复制代码
ggplot(liver.df, aes(x = cells, y = PRL)) + geom_point(col = "red") +
  labs(title = "Cells vs PRL", x = "Number of Cells", y = "PRL Response")

选定x轴为cells,y轴为PRL,使用红颜色绘制散点,labs标签用于标题和x、y轴名称的显示。

  1. 密度图绘制:
R 复制代码
ggplot(liver.df, aes(x = PRL, colour = exper, fill = exper)) +
  geom_density(alpha = 0.5) + xlim(-20,40) + 
  labs(title = "Density of PRL", x = "PRL Response", y = "Density")

使用liver.df数据框,aes选定x轴且告诉r语言我们要分别对exper的变量填色,透明度用alpha=0。5调整,x的可视范围调为-20到40,再对标题等进行名称显示。

  1. 多张散点图绘制:
R 复制代码
ggplot(liver.df, aes(x = PRL, y = ARL, color = exper)) +
  geom_point() + facet_wrap(section ~ exper) + theme_minimal()

命令 facet_wrap(section ~ exper) 按照章节和实验分割散点图,theme_minimal() 将绘图风格改为极简主题(例如,它移除了灰色背景)。

  1. 回归线绘制:
R 复制代码
ggplot(liver.df, aes(x = cells, y = ARL, colour = exper)) + geom_point() +
      labs(title = "Regression of ARL on cells", 
      x = "Number of Injected Cells", y = "ARL Response") +
      geom_smooth(method = 'lm', formula = y ~ x)

我们为每个实验在细胞上绘制ARL的回归图,使用geom_smooth(method = 'lm'),color根据exper选择不同颜色。

  1. 箱形图:
R 复制代码
ggplot(liver.df, aes(y = PRL, x = exper, fill = exper)) +
      geom_boxplot()  +
      labs(y = "PRL Response", x = "Experiment")

使用 geom_boxplot()生成各实验的 PRL 方框图。

ggplot2数据可视化官方文档

  1. the ggplot reference site: Function reference • ggplot2

  2. this ggplot2 Tutorial (short version and part 1-3): How to make any plot in ggplot2? | ggplot2 Tutorial

相关推荐
随缘而动,随遇而安7 分钟前
第五十二篇 浅谈ETL系统设计
大数据·数据仓库·数据分析·数据库开发·数据库架构
杨超越luckly1 小时前
HTML应用指南:利用GET请求获取微博签到位置信息
大数据·信息可视化·数据分析·html·html5
云天徽上10 小时前
【数据可视化-21】水质安全数据可视化:探索化学物质与水质安全的关联
安全·机器学习·信息可视化·数据挖掘·数据分析
谁家有个大人11 小时前
Python数据清洗笔记(上)
开发语言·笔记·python·数据分析
Jayen H12 小时前
数据分析:用Excel做周报
数据挖掘·数据分析
袁袁袁袁满15 小时前
《巧用DeepSeek快速搞定数据分析》书籍分享
数据挖掘·数据分析
echoVic15 小时前
PixiJS 源码揭秘 - 8. 插件机制深度解析
前端·源码·数据可视化
穆易青15 小时前
2025.04.23【探索工具】| STEMNET:高效数据排序与可视化的新利器
python·信息可视化·数据分析·ordering·visualisation
AI大模型顾潇17 小时前
[特殊字符] 大模型对话风格微调项目实战——模型篇 [特殊字符]✨
人工智能·算法·机器学习·数据挖掘·大模型·微调·ai大模型
lilye6618 小时前
精益数据分析(16/126):掌握关键方法,探寻创业真谛
人工智能·数据挖掘·数据分析