原文地址
https://www.r-graph-gallery.com/128-ring-or-donut-plot.html
本文展示的环形图主要是基于geom_rect()
函数实现,我们先看一下ggplot2帮助文档中的例子
查看帮助文档
help(package="ggplot2")
重复帮助文档中的例子
第一步:构建数据集
df <- data.frame(x = rep(c(2, 5, 7, 9, 12), 2),
y = rep(c(1, 2), each = 5),
z = factor(rep(1:5, each = 2)),
w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2))
df
第二步:画图
library(ggplot2)
ggplot(df,aes(xmin=x-w/2,xmax=x+w/2,
ymin=y,ymax=y+1))+
geom_rect(aes(fill=z),color="grey50")+
theme_bw()
![](https://img.haomeiwen.com/i6857799/ea38403d1b5cd81f.png)
这个例子构造的数据集稍微有点复杂,不太好理解
下面用文章开头提到的链接的数据,数据简单相对好理解
第一步:构造数据集
df<-data.frame(category=c("A","B","C"),
count=c(10,60,30))
df$fraction<-df$count/sum(df$count)
df$ymax<-cumsum(df$fraction)
df$ymin<-c(0,head(df$ymax,n=-1))
第二步:画图
ggplot(df,aes(ymax=ymax,ymin=ymin,
xmax=4,xmin=3))+
geom_rect(aes(fill=category))+
theme_bw()
![](https://img.haomeiwen.com/i6857799/2fa0e19c569ddaa7.png)
变成环形用到的是
coord_polar()
函数
ggplot(df,aes(ymax=ymax,ymin=ymin,
xmax=4,xmin=3))+
geom_rect(aes(fill=category))+
theme_bw()+
xlim(2,4)+
coord_polar(theta="y")
![](https://img.haomeiwen.com/i6857799/f85bba8e353d803a.png)
添加文本标签,修改一些细节
df$labelPosition<-(df$ymax + df$ymin)/2
df$label<-paste0(df$category,"\n value: ",df$count)
ggplot(df,aes(ymax=ymax,ymin=ymin,
xmax=4,xmin=3))+
geom_rect(aes(fill=category))+
geom_label(x=3.5,aes(y=labelPosition,label=label),size=4)+
scale_fill_brewer(palette = 4)+
coord_polar(theta = "y")+
xlim(2,4)+
theme_void()+
theme(legend.position = "none")
![](https://img.haomeiwen.com/i6857799/3eab7b2599ab529a.png)
调整圆环的粗细
ggplot(df,aes(ymax=ymax,ymin=ymin,
xmax=4,xmin=3))+
geom_rect(aes(fill=category))+
geom_label(x=2,aes(y=labelPosition,label=label,color=category),size=4)+
scale_fill_brewer(palette = 4)+
coord_polar(theta = "y")+
xlim(-1,4)+
theme_void()+
theme(legend.position = "none")
![](https://img.haomeiwen.com/i6857799/a7f57d0c463d09f2.png)
欢迎大家关注我的微信公众号
小明的数据分析笔记本
![](https://img.haomeiwen.com/i6857799/ce56111c7b548a88.jpg)
网友评论