R语言ggplot2环形图小例子

作者: 小明的数据分析笔记本 | 来源:发表于2020-01-07 22:09 被阅读0次
原文地址

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()
image.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()
image.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")
image.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")
image.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")
image.png

欢迎大家关注我的微信公众号
小明的数据分析笔记本

公众号二维码.jpg

相关文章

网友评论

    本文标题:R语言ggplot2环形图小例子

    本文链接:https://www.haomeiwen.com/subject/bepdactx.html