ggplot2包基本绘图(3)-饼图与旭日图

ggplot2包是目前R语言数据可视化的主力包,本文尝试将常见的数据可视化图(excel)中的图以ggplot2包的函数加以呈现。数据来源主要为tidyverse包中的mpg数据集

饼图与旭日图(空心圆圈)

#饼图,利用极坐标方式
library(tidyverse)
 dat3<-mpg%>%group_by(drv)%>%summarize(mean_cty=mean(cty)) 
 p1<- ggplot(dat3,aes(x="",y=mean_cty))+
    geom_col(aes(fill=drv))+
    coord_polar(theta="y")
  
 #旭日图  
#没有对应的对象,可通过极坐标变换
 dat3$id<-rep(2,3) #增加一个人为分组
 dat_temp<-data.frame(id=rep(1,3),drv=rep(NA,3),mean_cty=rep(0,3))
 dat4<-rbind(dat3,dat_temp)
 p2<-ggplot(dat4,aes(x=id,y=mean_cty))+
    geom_col(aes(fill=drv),position="stack")+
    coord_polar(theta="y")+
        #格式修改
    theme(axis.text = element_blank(),
          axis.title=element_blank(),
          axis.ticks=element_blank(),
          panel.grid=element_blank(),
                    )+
   scale_fill_discrete(na.translate=F)+ #不显示多加的drv=NA
    geom_text(aes(label=c("14.3","19.9","14.1",rep(NA,3))),
              position=position_stack(0.5)) #添加数值标注

#一页多图
  library(grid)
  grid.newpage()
  pushViewport(viewport(layout = grid.layout(1,2)))
  vplayout = function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
  print(p1, vp = vplayout(1, 1))
  print(p2, vp = vplayout(1, 2))

ggplot2包基本绘图(3)-饼图与旭日图_第1张图片
旭日图实际上没什么用,

饼图形状

通过设置geom_col里面的postion参数dodge、stack、fill再coord_polar转换坐标系后,会有不同的效果。

position=dodge

ggplot2包基本绘图(3)-饼图与旭日图_第2张图片

position=stack

ggplot2包基本绘图(3)-饼图与旭日图_第3张图片

position=fill

ggplot2包基本绘图(3)-饼图与旭日图_第4张图片

旭日图的大功效

旭日图展示单组比例意义不大,并不突出,但是如果有更多的分类变量,比如微生物分类学中,在不同分类水平上(门、纲、目、属等多个水平)上看不同物种的相对丰度,似乎比较有用
ggplot2包基本绘图(3)-饼图与旭日图_第5张图片
差不多的代码如下

 dat3<-mpg%>%group_by(year,drv)%>%summarize(mean_cty=mean(cty))
ggplot(dat3,aes(x=year,y=mean_cty,fill=drv))+geom_col(position="fill")+
  coord_polar(theta="y") +#格式修改
 theme(axis.text = element_blank(),
       axis.title=element_blank(),
       axis.ticks=element_blank(),
       panel.grid=element_blank())+#
   geom_text(aes(label=round(mean_cty,2)),position=position_fill(0.5)
             ) #添加数值标注

由于数据量的原因,只能显示一个概况,但是实际应该这么操作并不复杂了。数据多的时候可以不标注数值。
ggplot2包基本绘图(3)-饼图与旭日图_第6张图片

你可能感兴趣的:(R,ggplot2)