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

相关推荐
时序之心1 小时前
时序论文速递:覆盖时间序列预测、分类、异常检测及交叉应用!(10.20-10.24)
人工智能·分类·数据挖掘·论文·时间序列
全栈探索者4 小时前
numpy基础
python·数据分析·numpy
追风少年ii4 小时前
脚本优化--visium的细胞niche与共定位(R版本)
数据分析·r语言·空间·单细胞
Jmayday5 小时前
python数据分析项目之:房地产数据可视化分析
python·信息可视化·数据分析
成长痕迹13 小时前
【Python与Matlab数据分析对比】
python·matlab·数据分析
学掌门13 小时前
数据分析过程中,发现数值缺失,怎么办?
数据挖掘·数据分析
Jackiejin52613 小时前
WPS表格选择性粘贴快捷键怎么使用?WPS如何给表格某一行都加上指定数字?
数据分析·excel·wps
B站_计算机毕业设计之家14 小时前
python电商商品评论数据分析可视化系统 爬虫 数据采集 Flask框架 NLP情感分析 LDA主题分析 Bayes评论分类(源码) ✅
大数据·hadoop·爬虫·python·算法·数据分析·1024程序员节
周杰伦_Jay15 小时前
【向量检索与RAG全流程解析】HNSW原理、实践及阿里云灵积DashScope嵌入
人工智能·阿里云·数据挖掘·云计算·database·1024程序员节
西***634719 小时前
怕故障?怕扩展难?分布式可视化控制:给足场景安全感
分布式·数据可视化