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

相关推荐
He_Donglin5 小时前
Data Mining|缺省值补全实验
人工智能·机器学习·数据挖掘
森哥的歌5 小时前
SVG 知识详解:从入门到精通
svg·数据可视化·前端开发·矢量图形·web图形
胡耀超7 小时前
图像颜色理论与数据挖掘应用的全景解析
人工智能·python·opencv·计算机视觉·数据挖掘·视觉检测·pillow
kngines8 小时前
【PostgreSQL数据分析实战:从数据清洗到可视化全流程】附录-D. 扩展插件列表(PostGIS/PostgREST等)
数据库·postgresql·数据分析·pgvector·扩展插件·postgrest·向量数据
終不似少年遊*9 小时前
MindSpore框架学习项目-ResNet药物分类-数据增强
人工智能·深度学习·分类·数据挖掘·华为云·resnet·modelart
神洛华9 小时前
DAX权威指南2:CALCULATE 与 CALCULATETABLE
数据分析·powerbi
Mr.Winter`13 小时前
深度强化学习 | 图文详细推导软性演员-评论家SAC算法原理
人工智能·深度学习·神经网络·机器学习·数据挖掘·机器人·强化学习
万能程序员-传康Kk19 小时前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
新中地GIS开发老师1 天前
【Cesium入门教程】第七课:Primitive图元
arcgis·信息可视化·gis开发·webgis·地理信息系统·地理信息科学
正在走向自律1 天前
Python 数据分析与可视化:开启数据洞察之旅(5/10)
开发语言·人工智能·python·数据挖掘·数据分析