使用ggplot2减少对称图的代码

时间:2018-06-15 11:44:04

标签: r ggplot2

我经常有如下图,它们是对称的,所以除了数据之外,x和y轴基本相似,但我总是需要分别定义geom_hlinegeom_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 个答案:

答案 0 :(得分:0)

我只是根据这个问题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()