您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# R语言基础绘图函数散点图的示例分析
## 1. 引言
散点图(Scatter Plot)是数据可视化中最基础且重要的图表类型之一,用于展示两个连续变量之间的关系。在R语言中,基础绘图系统(base graphics)提供了简单而强大的函数来创建散点图。本文将深入探讨`plot()`函数在散点图绘制中的应用,结合代码示例和实际数据集进行演示。
---
## 2. 基础散点图绘制
### 2.1 基本语法
```r
plot(x, y, main = "标题", xlab = "X轴标签", ylab = "Y轴标签", col = "颜色", pch = 点形状)
以R内置的mtcars
数据集为例:
data(mtcars)
plot(mtcars$wt, mtcars$mpg,
main = "汽车重量与油耗关系",
xlab = "重量(吨)",
ylab = "油耗(英里/加仑)",
col = "blue",
pch = 16)
图1:基础散点图示例
pch
:控制点的形状(1-25为预设形状)cex
:控制点的大小(默认1)col
:控制颜色(支持颜色名称/十六进制/RGB)# 不同点形状示例
plot(1:25, rep(1,25), pch = 1:25, cex = 2, col = "red")
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轴
model <- lm(mpg ~ wt, data = mtcars)
plot(mtcars$wt, mtcars$mpg)
abline(model, col = "red", lwd = 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)
plot(mtcars$wt, mtcars$mpg)
text(mtcars$wt, mtcars$mpg,
labels = rownames(mtcars),
pos = 4, cex = 0.6)
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")
pairs(~mpg+wt+disp+hp, data = mtcars,
col = as.factor(mtcars$cyl))
data(iris)
summary(iris)
plot(iris$Sepal.Length, iris$Petal.Length,
col = iris$Species,
pch = as.numeric(iris$Species))
library(MASS)
z <- kde2d(iris$Sepal.Length, iris$Petal.Length)
contour(z, add = TRUE)
# 使用半透明色
plot(x, y, col = rgb(0, 0, 1, alpha = 0.3), pch = 16)
# 使用jitter添加随机扰动
plot(jitter(x), jitter(y))
# 使用平滑散点图
smoothScatter(x, y)
虽然ggplot2提供了更现代的语法,但基础绘图系统仍有其优势: - 更轻量级,适合快速探索 - 更直接的底层控制 - 无需额外安装包
# ggplot2等效代码
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
geom_smooth(method = "lm")
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 |
”`
(注:实际文章应包含完整的代码执行结果和更详细的解释,此处为简化版框架。图片链接需替换为实际生成的图表。)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。