条形图(bar chart)是用宽度相同的条形的高度或长短来表示数据多少的图形。成对比较的条形图很浅显易懂的展示两组数据的占比情况。下面我们用ggplot2绘制演示:
# 加载R包
library(tidyverse)
library(ggthemes)
# 读取演示数据,中文数据读取
data <- read.csv("data.csv", header = T, encoding = "UTF-8")
# 绘图
data %>%
ggplot(aes(x = level, fill = gender)) +
# 建立第一组条形图
geom_col(data = filter(x, gender == "男"),
aes(y = percent)) +
# 建立另一组条形图
geom_col(data = filter(x, gender == "女"),
aes(y = -1 * percent)) +
# 建立第一组条形图标签
geom_text(data = filter(x, gender == "男"),
aes(y = percent, label = percent),
hjust = -.1) +
# 建立另一组条形图标签
geom_text(
data = filter(x, gender == "女"),
aes(y = -1 * percent, label = percent),
hjust = 1.1
) +
# 设置y轴范围
expand_limits(y = c(-17, 17)) +
# 替换Y轴标签,用绝对值表示
scale_y_continuous(breaks = seq(-15, 15, by = 5),
labels = abs) +
# 轴翻转
coord_flip() +
# 主题
theme_few() +
# 图例位置
guides(fill = guide_legend(title = '')) +
theme(legend.position="top") +
labs(
x = "教育水平",
y = "人群中所占比例",
fill = "Gender",
title = paste0("20XX年最高教育程度人口百分比")
)
绘图中间用到了分别建立两组条形图通过拼接实现比较,其中coord_flip()
做了x轴和y轴翻转,其他部分和常规的ggplot2基本操作一致。
参考资料:
1.https://www.r-bloggers.com/writing-functions-to-automate-repetitive-plotting-tasks-in-ggplot2/