⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

R ggplot2入门

R语言 ggplot2 数据可视化入门 · 难度:进阶 · +15XP

R语言 ggplot2 数据可视化入门

ggplot2是R语言中最流行的数据可视化包,基于图形语法(Grammar of Graphics)理论构建。它的核心理念是将图表分解为数据、映射和几何对象等独立组件,通过层层叠加的方式构建复杂图表,比R基础绘图的代码更清晰、扩展性更强。

安装与基本用法

# 安装ggplot2(只需一次)
install.packages("ggplot2")

# 加载包 library(ggplot2)

# 基本模板 # ggplot(data, aes(x, y)) + geom_xxx() ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() # 含义:数据=mtcars,x轴=车重(wt),y轴=油耗(mpg),几何=散点

核心概念:图形语法三要素

要素说明示例
Data(数据)数据框,每一行是一个观测mtcars
Mapping(映射)aes() 将变量映射到视觉属性aes(x=wt, y=mpg, color=cyl)
Geometry(几何)图形的绘制方式geom_point()geom_line()

常用几何对象(geom)

# 散点图
ggplot(mtcars, aes(wt, mpg)) + geom_point()

# 折线图 ggplot(mtcars, aes(wt, mpg)) + geom_line()

# 柱状图 ggplot(mtcars, aes(factor(cyl))) + geom_bar()

# 箱线图 ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot()

# 直方图 ggplot(mtcars, aes(mpg)) + geom_histogram(bins = 10)

# 密度曲线 ggplot(mtcars, aes(mpg)) + geom_density()

# 平滑趋势线 ggplot(mtcars, aes(wt, mpg)) + geom_point() + geom_smooth(method = "lm") # 线性回归线

美化图表:颜色与分面

# 按分类变量着色
ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point(size = 3)

# 按分类变量分面(facet_wrap 单变量分面) ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl) # 每个cyl值一个子图

# facet_grid 双变量分面 ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_grid(am ~ cyl) # 行=变速箱类型,列=气缸数

# 自定义主题和标签 ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) + geom_point(size = 3) + labs(title = "汽车重量与油耗关系", subtitle = "按气缸数着色", x = "重量 (1000 lbs)", y = "油耗 (mpg)", color = "气缸数") + theme_minimal() # 极简主题

叠加图层

ggplot2的核心优势在于图层叠加

# 散点 + 回归线 + 标题
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(color = hp), size = 3) +    # 散点,按马力着色
  geom_smooth(method = "lm", se = TRUE) +     # 回归线 + 置信区间
  scale_color_gradient(low = "blue", high = "red") +
  labs(title = "车重-油耗-马力三维分析") +
  theme_bw()

# 保存图片 ggsave("analysis.png", width = 8, height = 6, dpi = 150)

实战练习

  1. 用mtcars数据集绘制mpg vs hp的散点图,按cyl着色
  2. 绘制不同气缸数(cyl)的mpg箱线图
  3. 用facet_wrap按cyl分面展示散点图
  4. 叠加geom_point和geom_smooth创建带趋势线的散点图
  5. 自定义图表标题、坐标轴标签和主题样式

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 71 篇
0 完成
🔥 0