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