代码之家  ›  专栏  ›  技术社区  ›  drmariod

使用ggplot2[重复]减少对称绘图的代码

  •  0
  • drmariod  · 技术社区  · 6 年前

    geom_hline geom_vline 分开,即使它们几乎相同。同样的原因 scale_x_continous

    set.seed(1)
    df <- data.frame(x=rnorm(200, sd=3),
                     y=rnorm(200, sd=3))
    ggplot(df, aes(x=x, y=y)) +
      geom_hline(yintercept = c(-1, 0, 1), 
                 color=c("red", "grey", "red"), linetype=c('dashed', 'solid', 'dashed')) + 
      geom_vline(xintercept = c(-1, 0, 1), 
                 color=c("red", "grey", "red"), linetype=c('dashed', 'solid', 'dashed')) + 
      geom_point(size=2, shape=21, color='grey20', alpha=.3) +
      scale_x_continuous('my y', 
                         breaks=seq(-100,100,4), minor_breaks=seq(-100,100,1), 
                         limits=c(-13.5, 13.5)) + 
      scale_y_continuous('my y', 
                         breaks=seq(-100,100,4), minor_breaks=seq(-100,100,1), 
                         limits=c(-13.5, 13.5))
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   drmariod    6 年前

    我只是根据这个问题想出来的 How can I combine multiple ggplot2 elements into the return of a function? .

    set.seed(1)
    df <- data.frame(x=rnorm(200, sd=3),
                     y=rnorm(200, sd=3))
    
    baseDesign <- function(line_colors = c("red", "grey", "red"),
                    line_types = c('dashed', 'solid', 'dashed'),
                    plot_breaks = seq(-100,100,4),
                    plot_minor_breaks = seq(-100,100,1),
                    plot_limits = c(-13.5, 13.5)) {
      p <- list(geom_hline(yintercept = c(-1, 0, 1), 
                        color=line_colors, linetype=line_types),
        geom_vline(xintercept = c(-1, 0, 1), 
                   color=line_colors, linetype=line_types),
        scale_x_continuous(expression(log[2]*" SILAC ratio (female - male)"), 
                           breaks=plot_breaks, minor_breaks=plot_minor_breaks, 
                           limits=plot_limits),
        scale_y_continuous(expression(log[2]*" LFQ (female - male)"), 
                           breaks=plot_breaks, minor_breaks=plot_minor_breaks, 
                           limits=plot_limits))
      return(p)
    }
    ggplot(df, aes(x=x, y=y)) +
      geom_point(size=2, shape=21, color='grey20', alpha=.3) + 
      baseDesign()