Untitled

02234511王叶新

2025-12-03

library(ggplot2)

绘图任务一:基础几何对象与映射

# 基础散点图

ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point()  # 几何对象:散点

按物种着色的散点图

ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
  geom_point()  # 颜色随Species变化

箱线图

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()  # 几何对象:箱线图

绘图任务二:添加趋势线与分面

#添加线性趋势线

# 散点图 + 线性趋势线(不带误差带)
ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() +  # 散点
  geom_smooth(method = "lm", se = FALSE) +  # 线性回归趋势线(se=FALSE关闭误差带)
  ggtitle("鸢尾花萼片长度与花瓣长度的线性趋势")
## `geom_smooth()` using formula = 'y ~ x'

按物种分组的散点+趋势线

ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +  # 每个物种单独画趋势线
  ggtitle("不同鸢尾花物种的萼片-花瓣长度线性趋势")
## `geom_smooth()` using formula = 'y ~ x'

分面展示每个物种的散点+趋势线

ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  facet_wrap(~ Species) +  # 按Species分面
  ggtitle("各鸢尾花物种的萼片-花瓣长度关系(分面展示)")
## `geom_smooth()` using formula = 'y ~ x'