Chapter 1 Notes for ggplot2

  1. stat_function: add function curve
stat_function(color = 'blue', fun=dunif, args=list(0,1),size=1.2)
  1. geom_segment: segment plot
  ggplot(d2,
        aes(x = lower,  #横向线段
            xend  = upper,
            y     = county,
            yend  = county))+
      geom_segment(lwd=1, alpha=0.5) +
      labs(x='mean', y="county", title='95% Credible Intervals') +
      scale_color_brewer(palette='Set1') +
      scale_y_reverse() +
      theme_bw()

Remark: change segment line type, color and width:
- scale_linetype_manual(values=c("twodash", "dotted")) #("solid", "twodash", "dotted", "longdash", "dotdash", "dashed", "blank")
- scale_color_manual(values=c('#999999','#E69F00'))
- scale_size_manual(values=c(1, 1.5))

  1. theme:
  • theme(legend.position='none'): hide legend,
  • axis.title.y = element_blank(): remove y axis name (or ylab())
  • axis.text.x = element_text(angle = 45): adjust x axis text angle
  • plot.title = element_text(hjust = 0.5): center title
  • text=element_text(size=15): change font size
    • use base_size = 15 in theme_xx()
    • use family = "xxx" to change font family
  1. ggpubr::arrange(p1, p2, ..., ncol = ): plot multiple ggplots in one figure
  • Or gridExtra::grid.arrange(..., ncol = )
  • Or require(cowplot)
myplots = vector("list", n) 
myplot[[i]]<- ggplot(...) 
plot_grid(plotlist=myplots)
  • Or require(grid)
        grid.newpage()  #新建图表版面
        pushViewport(viewport(layout = grid.layout(2,2))) #将版面分成2*2矩阵
        vplayout <- function(x,y){viewport(layout.pos.row = x, layout.pos.col = y)}  
        print(chart3, vp = vplayout(1,1:2))   #将(1,1)和(1,2)的位置画图chart3
        print(chart2, vp = vplayout(2,1))     #将(2,1)的位置画图chart2          
        print(chart1 , vp = vplayout(2,2))    #将(2,2)的位置画图chart1
  1. scale_y_log10(): tale log of y axis
  2. geom_hline(), geom_vline(), geom_abline
    geom_hline(yintercept=25, color="orange", size=1) +
    geom_vline(xintercept=3, color="orange", size=1
  1. geom_errorbar(): boxplot or scatterplot add confidence interval
        geom_errorbar(aes(ymin = mean_gain-1.96*sd_gain, 
                          ymax = mean_gain+1.96*sd_gain, colour = Diet), data = ChickError)
  1. forcats::fct_inorder: Reorder factor levels by first appearance, frequency, or numeric order
a = factor(rep(c("Roads", "Canals", "Early railways", "Railways"), each = 3))
a %>% forcats::fct_inorder() %>% levels()
## [1] "Roads"          "Canals"         "Early railways" "Railways"