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

相关推荐
Leo.yuan几秒前
数据分析师如何构建自己的底层逻辑?
大数据·数据仓库·人工智能·数据挖掘·数据分析
zhangfeng11333 小时前
python 数据分析 单细胞测序数据分析 相关的图表,常见于肿瘤免疫微环境、细胞亚群功能研究 ,各图表类型及逻辑关系如下
开发语言·python·数据分析·医学
UI罐头3 小时前
如何选择数据可视化工具?从设计效率到图表表现力全解读
信息可视化·数据分析·数据工具
超龄超能程序猿9 小时前
使用 Python 对本地图片进行图像分类
开发语言·人工智能·python·机器学习·分类·数据挖掘·scipy
Favor_Yang1 天前
SQL Server通过存储过程实现HTML页面生成
前端·信息可视化·sqlserver·存储过程
❀͜͡傀儡师1 天前
GoView 低代码数据可视化
信息可视化·go-view
java1234_小锋1 天前
基于Python的旅游推荐协同过滤算法系统(去哪儿网数据分析及可视化(Django+echarts))
python·数据分析·旅游
视频砖家1 天前
观众信息设置与统计(视频高级分析与统计功能)
数据分析·视频观看分析·视频数据分析
LabEx1 天前
科研数据可视化核心技术:基于 AI 与 R 语言的热图、火山图及网络图绘制实践指南
人工智能·信息可视化·r语言·r语言绘图·乐备实·labex·科研数据绘图