R 语言绘图教程案例
下面给你整理一套最常用、最实用、直接能跑代码的 R 语言绘图案例,全部基于 ggplot2(行业标准),从基础到进阶,适合做报告、论文、数据分析展示。
你复制代码到 RStudio 就能直接出图。
一、环境准备(先运行)
library(ggplot2)
library(dplyr)
data(iris) # 经典鸢尾花数据
data(mtcars) # 汽车数据
1. 散点图(最常用)
基础散点图
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
labs(title = "花萼长度 vs 花萼宽度", x = "长度", y = "宽度")
分组上色 + 拟合曲线
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point(size = 2, alpha = 0.7) +
geom_smooth(method = "lm", se = FALSE) +
theme_minimal()
2. 柱状图 / 条形图
简单柱状图
ggplot(mtcars, aes(x = factor(cyl))) +
geom_bar(fill = "steelblue") +
labs(title = "不同气缸数车辆数量", x = "气缸数", y = "数量")
分组柱状图
ggplot(mtcars, aes(x = factor(cyl), fill = factor(am))) +
geom_bar(position = "dodge") +
labs(title = "变速箱与气缸分布", fill = "变速箱(0/1)")
3. 箱线图(看分布、异常值)
ggplot(iris, aes(x = Species, y = Petal.Length, fill = Species)) +
geom_boxplot() +
theme_bw() +
labs(title = "不同品种花瓣长度分布")
4. 直方图 / 密度图
直方图
ggplot(iris, aes(x = Petal.Length)) +
geom_histogram(bins = 20, fill = "orange", alpha = 0.7)
分组密度图
ggplot(iris, aes(x = Petal.Length, fill = Species)) +
geom_density(alpha = 0.5)
5. 折线图(时序/趋势)
# 构造简单时序数据
df <- data.frame(
time = 1:20,
value = cumsum(rnorm(20))
)
ggplot(df, aes(x = time, y = value)) +
geom_line(color = "red", linewidth = 1) +
geom_point()
6. 热图(相关性矩阵)
cor_df <- round(cor(iris[,1:4]), 2)
cor_df <- as.data.frame(as.table(cor_df))
ggplot(cor_df, aes(x = Var1, y = Var2, fill = Freq)) +
geom_tile() +
geom_text(aes(label = Freq), color = "white") +
scale_fill_gradient2(low = "blue", high = "red") +
theme_minimal()
7. 小提琴图(比箱线图更详细)
ggplot(iris, aes(x = Species, y = Sepal.Width, fill = Species)) +
geom_violin(alpha = 0.6) +
geom_jitter(size = 0.5)
8. 分面图(多子图一起展示)
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
facet_wrap(~Species) +
theme_bw()
9. 误差棒图(均值±标准差)
iris_sum <- iris %>%
group_by(Species) %>%
summarise(
mean = mean(Petal.Length),
sd = sd(Petal.Length)
)
ggplot(iris_sum, aes(x = Species, y = mean, fill = Species)) +
geom_col() +
geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = 0.2)
10. 饼图(ggplot 风格)
df <- table(mtcars$cyl) %>% data.frame()
colnames(df) <- c("cyl", "count")
ggplot(df, aes(x = "", y = count, fill = factor(cyl))) +
geom_col() +
coord_polar("y") +
theme_void()
11. 高级:气泡图(散点+大小+颜色)
ggplot(mtcars, aes(x = wt, y = mpg, size = hp, color = factor(cyl))) +
geom_point(alpha = 0.7) +
scale_size(range = c(2, 10)) +
labs(title = "重量-油耗-马力-气缸")
12. 论文级美化模板(通用)
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
geom_point(size = 2) +
geom_smooth(method = "lm", se = T) +
labs(
title = "鸢尾花性状关系",
subtitle = "花萼长度与花瓣长度线性回归",
x = "Sepal Length (cm)",
y = "Petal Length (cm)",
color = "Species"
) +
theme_classic() +
theme(
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)
)
浙公网安备 33010602011771号