前言
饼图,是将总体看作一个圆,按照各分类的占比情况将圆划分大小不同的扇形,以弧度的大小来表示某一分类的占比。
饼图可以让人快速的了解各分类的情况,但一般分类的数量不能太多,太多会导致圆被切割为很多块,不利于展示
在饼图中,通常会将占比最大的分类放置在最显眼的地方,即 12
点钟方向的右边,而第二大占比放置在 12
点钟方向的左边。其余的分类依据逆时针方向放置
示例
使用 ggplot2
绘制饼图,首先需要将所有数据绘制成一条柱状图,并通过分类变量填充不同的颜色
p <- group_by(mpg, class) %>%
summarise(percent = n() / nrow(mpg)) %>%
ggplot(aes(x = factor(1), y = percent, fill = class)) +
geom_col(colour = "white")
然后根据 y
轴,转换为极坐标系
p + coord_polar(theta = "y")
添加百分比注释
p +
coord_polar(theta = "y", start = 1.65) +
geom_text(aes(label = paste0(round(percent * 100, 2), "%")),
position = position_fill(vjust = 0.5)) +
theme(
panel.background = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()
)
也可以使用 graphics
包的 pie
函数绘制饼图
df <- group_by(mpg, class) %>%
summarise(percent = n() / nrow(mpg)) %>%
arrange(desc(percent))
pie(df$percent)
将标签替换成我们的分类标签
pie(df$percent, labels = df$class)
通过设置更小的 edges
参数的值,能够让圆形变成多边形
pie(df$percent, labels = df$class, edges = 22)
使用 density
和 angle
绘制密度线及其角度
pie(df$percent, labels = df$class, edges = 22,
density = 18, angle = c(20,90,30,100,120,180,45))
更换颜色
library(RColorBrewer)
my_color <- brewer.pal(7, "Set2")
pie(df$percent, labels = df$class, col = my_color)
为每个标签添加占比
pie(df$percent, labels = with(df, paste0(class, "(", round(percent, 2) * 100, "%)")),
col = my_color)
饼图变形
甜甜圈图
甜甜圈图或者说圆环图,本质上只是将饼图的中心挖空。如
p <- group_by(mpg, class) %>%
summarise(percent = n() / nrow(mpg)) %>%
ggplot(aes(x = 1, y = sort(percent, decreasing = TRUE), fill = class)) +
geom_col(colour = "white")
p +
coord_polar(theta = "y", start = 1.65) +
geom_text(aes(label = paste0(round(percent * 100, 2), "%")),
position = position_fill(vjust = 0.5)) +
xlim(c(-1, 2)) +
theme(
panel.background = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()
)
不同于饼图聚焦于各扇形的面积,甜甜圈图则是着重于强调圆环的长度,同时空间利用率更高,我们可以将注释放置在圆环内
p <- group_by(mpg, class) %>%
summarise(percent = n() / nrow(mpg)) %>%
ggplot(aes(x = 2, y = sort(percent, decreasing = TRUE), fill = class)) +
geom_col(colour = "white")
p +
coord_polar(theta = "y", start = 1.65) +
geom_text(aes(x = 1, label = paste0(class, "(", round(percent * 100, 2), "%)")),
position = position_fill(vjust = 0.5), size = 3, hjust = 0.5) +
xlim(c(-1, 3)) +
theme(
panel.background = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()
)