ggplot2与"画饼"
本次主角:依旧是饼图(pie chart)。
续上篇👉pie图是一种非常糟糕的信息展示方式,一般不建议使用
本期使用ggplot2的方法制作pie图。
ggplot2无直接制作pie图的方法,但是,可以将条形图进行极坐标变换后,就能实现饼图绘制了。
下面介绍ggplot2如何“画饼”,
第1步,制作条形图
# 加载 ggplot2 包
library(ggplot2)# 创建数据
df <- data.frame(
value = c(1, 2, 3, 4, 5),
group = paste0("slice", 1:5)
)
# ggplot2画饼
p1 <- ggplot(df, aes(x = "", y = value, fill = group)) + # 定义数据和映射关系,x 轴为空,y 轴为 value,填充颜色为 group
geom_bar(stat = 'identity', position = 'stack') + # 使用柱状图
geom_text(
aes(label = sprintf("%.2f%%", (value / sum(value) * 100))), # 添加百分比标签,格式化为百分比并保留两位小数
position = position_stack(vjust = 0.5) # 设置文本位置,垂直居中对齐
)
p1
第2步,条形图转饼图
使用ggplot2 coord_polar,将柱状图转换为饼图。
coord_polar(theta = "y") # ❤️使用极坐标,将条形图转换为饼图
第3步,饼图美化
去除背景、网格线、自定义颜色等。
p1 + coord_polar(theta = "y") +
geom_text(
aes(label = sprintf("%.2f%%", (value / sum(value) * 100))),
position = position_stack(vjust = 0.5)
) +
theme_void() + # 使用空主题,去除背景、网格线等
theme(legend.position = "bottom") + # 设置图例位置为底部
scale_fill_manual(
values = c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73"), # 手动设置填充颜色
guide = guide_legend(nrow = 2) # 设置图例标签2行显示
)
-END-
👇加入学习(收费,请备注:169)