ggplot一张图的诞生(1)-柱状图

ggplot一张图的诞生(1)

gzh:BBio

两个要求

#坐标轴截断
#添加标准误差线

制作过程

  • 准备数据

    df<-data.frame(
      food=rep(c("番茄","红薯","鲫鱼"),each=9),
      filed=rep(c(LETTERS[1:3]),9),
      date=rep(c(rep(c("day1","day2","day3"),each=3)),3),
      price=c(
        round(c(runif(3,3.2,3.8),runif(3,7.3,8.0),runif(3,9.3,10)),2),
        round(c(runif(3,2.8,2.9),runif(3,2.9,3.5),runif(3,3.5,4.3)),2),
        round(c(runif(3,8,9),runif(3,17,18),runif(3,19,20)),2))
    )
    
  • 计算标准差和标准误差

    library(Rmisc)
    summary.df<-summarySE(df,measurevar="price",groupvars=c("food","date"))
    
  • 绘图

    library(ggplot2)
    p1<-ggplot(summary.df,aes(date,price,fill=food))+
      geom_col(position="dodge",alpha=0.8)+
      facet_grid(.~food)
    
image
  • 调整1

    p1<-p1+labs(x=NULL,y="价格(元)/500g",fill="Food")+
      ggtitle("食品价格走势")+
      theme(plot.title=element_text(hjust=0.5))
    
image
  • 调整2

    p1<-p1+scale_x_discrete(
      label=c("1月18日","2月2日","2月22日"))+
      theme(axis.text.x=element_text(angle=45,hjust=1))
    
image
  • 调整3

    p1<-p1+theme(strip.background=element_rect(fill="grey50"),panel.grid=element_blank())
    
image
  • 添加标准误差线

    p1<-p1+geom_errorbar(
      aes(ymin=price-se,ymax=price+se),width=.2,position=position_dodge(0.9))
    
image
  • 截断坐标轴

    split1<-p1+coord_cartesian(ylim=c(0,11))+
      theme(strip.background = element_blank(),
            strip.text = element_blank(),
            legend.position="none")+
      labs(title=NULL,y=NULL)
    split2<-p1+coord_cartesian(ylim=c(16.5,20))+
      theme(axis.text.x=element_blank(),
            axis.ticks.x=element_blank(),
            legend.position="none")+
      labs(y=NULL)
    
  • 拼接上下两部分

    library(grid)
    grid.newpage()
    pushViewport(viewport(layout=grid.layout(2,1)))
    vplayout = function(x, y){
      viewport(layout.pos.row=x, layout.pos.col=y)
    }
    print(split1, vp = vplayout(2, 1))
    print(split2, vp = vplayout(1, 1))
    
image

你可能感兴趣的:(ggplot一张图的诞生(1)-柱状图)