R语言基础绘图函数散点图的示例分析

发布时间:2021-11-22 14:47:40 作者:柒染
来源:亿速云 阅读:530
# R语言基础绘图函数散点图的示例分析

## 1. 引言

散点图(Scatter Plot)是数据可视化中最基础且重要的图表类型之一,用于展示两个连续变量之间的关系。在R语言中,基础绘图系统(base graphics)提供了简单而强大的函数来创建散点图。本文将深入探讨`plot()`函数在散点图绘制中的应用,结合代码示例和实际数据集进行演示。

---

## 2. 基础散点图绘制

### 2.1 基本语法
```r
plot(x, y, main = "标题", xlab = "X轴标签", ylab = "Y轴标签", col = "颜色", pch = 点形状)

2.2 使用内置数据集示例

以R内置的mtcars数据集为例:

data(mtcars)
plot(mtcars$wt, mtcars$mpg, 
     main = "汽车重量与油耗关系",
     xlab = "重量(吨)", 
     ylab = "油耗(英里/加仑)",
     col = "blue",
     pch = 16)

R语言基础绘图函数散点图的示例分析 图1:基础散点图示例


3. 参数详解

3.1 点属性控制

# 不同点形状示例
plot(1:25, rep(1,25), pch = 1:25, cex = 2, col = "red")

3.2 坐标轴调整

plot(mtcars$wt, mtcars$mpg,
     xlim = c(1, 6),  # X轴范围
     ylim = c(10, 35), # Y轴范围
     xaxt = "n")      # 不显示默认X轴
axis(1, at = seq(1, 6, by = 1)) # 自定义X轴

4. 高级定制技巧

4.1 添加回归线

model <- lm(mpg ~ wt, data = mtcars)
plot(mtcars$wt, mtcars$mpg)
abline(model, col = "red", lwd = 2) # 添加回归线

4.2 分组散点图

# 按气缸数分组着色
colors <- c("red", "green", "blue")[as.factor(mtcars$cyl)]
plot(mtcars$wt, mtcars$mpg, col = colors, pch = 16)
legend("topright", legend = levels(as.factor(mtcars$cyl)),
       col = c("red", "green", "blue"), pch = 16)

4.3 添加文本标注

plot(mtcars$wt, mtcars$mpg)
text(mtcars$wt, mtcars$mpg, 
     labels = rownames(mtcars),
     pos = 4, cex = 0.6)

5. 多图组合

5.1 par()函数设置

par(mfrow = c(2, 2)) # 2行2列布局
plot(mtcars$wt, mtcars$mpg, main = "图1")
plot(mtcars$disp, mtcars$mpg, main = "图2")
plot(mtcars$hp, mtcars$mpg, main = "图3")
plot(mtcars$qsec, mtcars$mpg, main = "图4")

5.2 矩阵散点图

pairs(~mpg+wt+disp+hp, data = mtcars,
      col = as.factor(mtcars$cyl))

6. 实际案例:鸢尾花数据集分析

6.1 数据探索

data(iris)
summary(iris)

6.2 多变量散点图

plot(iris$Sepal.Length, iris$Petal.Length,
     col = iris$Species,
     pch = as.numeric(iris$Species))

6.3 添加密度等高线

library(MASS)
z <- kde2d(iris$Sepal.Length, iris$Petal.Length)
contour(z, add = TRUE)

7. 常见问题与解决方案

7.1 重叠点处理

# 使用半透明色
plot(x, y, col = rgb(0, 0, 1, alpha = 0.3), pch = 16)

# 使用jitter添加随机扰动
plot(jitter(x), jitter(y))

7.2 大数据集优化

# 使用平滑散点图
smoothScatter(x, y)

8. 与ggplot2的简单对比

虽然ggplot2提供了更现代的语法,但基础绘图系统仍有其优势: - 更轻量级,适合快速探索 - 更直接的底层控制 - 无需额外安装包

# ggplot2等效代码
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() + 
  geom_smooth(method = "lm")

9. 结语

R语言的基础绘图系统为散点图提供了灵活多样的绘制方式。通过掌握plot()函数及其相关参数,可以完成从简单到复杂的数据可视化需求。建议读者在实际工作中: 1. 先使用基础绘图快速探索数据 2. 根据需求逐步添加定制元素 3. 对需要出版级质量的图形再考虑ggplot2等高级包

提示:本文所有代码已在R 4.2.0环境下测试通过,建议读者在RStudio中逐段运行体验效果。


附录:常用参数速查表

参数 说明 示例值
pch 点形状 1-25
cex 点大小 0.5-3
col 颜色 “red”, “#FF0000”
xlim X轴范围 c(0, 10)
main 标题 “我的散点图”
lwd 线宽 1-5

”`

(注:实际文章应包含完整的代码执行结果和更详细的解释,此处为简化版框架。图片链接需替换为实际生成的图表。)

推荐阅读:
  1. Python函数基础的示例分析
  2. python散点图之随机漫步的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

r语言

上一篇:Python的学习方向有哪些

下一篇:c语言怎么实现含递归清场版扫雷游戏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》