R 语言使用 ggplot2 绘制常见条形图
在 R 语言中,可以使用 ggplot2 的 geom_bar() 函数来绘制条形图。
1、单个条形图
library(ggplot2)
library(tidyverse)
# 设置中文正常显示
library(showtext)
showtext_auto()
set.seed(123)
# 生成数据
student_data <- data.frame(
student_id = 1:50,
subject = sample(c('语文', '数学', '英语', '物理'), 50, replace = TRUE),
grade = sample(c('不及格', '良好', '优秀'), 50, replace = TRUE)
)
# 单个条形图
ggplot(student_data, aes(x = subject)) + geom_bar()
2、多个条形图
# 多个条形图
ggplot(student_data, aes(x = subject, fill = grade)) + geom_bar(position = 'dodge')
3、堆积条形图
# 堆积条形图
ggplot(student_data, aes(x = subject, fill = grade)) + geom_bar()
4、百分比堆积条形图
# 百分比堆积条形图
ggplot(student_data, aes(x = subject, fill = grade)) + geom_bar(position = 'fill')