如何将geom_text定位到图像的顶部?

时间:2015-09-22 07:55:14

标签: r ggplot2

我有一个R脚本,我无法弄清楚如何将线性模型文本定位到图的顶部。

enter image description here

显然,该等式已被截断在图片的左侧。如何将它定位到屏幕的中央和顶部?

library('ggplot2')

# Convert a linear model to string
lm_eqn <- function(d)
{
    m <- lm(y ~ x, d);
    eq <- substitute(italic(y) == a + b * italic(x)*","~~italic(r)^2~"="~r2, 
                     list(a  = format(coef(m)[1], digits = 2), 
                          b  = format(coef(m)[2], digits = 2), 
                          r2 = format(summary(m)$r.squared, digits = 3)))
    as.character(as.expression(eq));
}

x <- c(1.000000, 1.000000, 512.000000, 0.007812, 0.500000, 128.000000, 0.031250, 8.000000, 1.000000, 0.125000, 1.000000, 0.001953, 1.000000, 512.000000, 1.000000, 1.000000, 1.000000, 0.031250, 8.000000, 1.000000, 1.000000, 1.000000, 2.000000, 0.007812, 32.000000, 1.000000, 128.000000, 2.000000, 0.500000, 2.000000)
y <- c(1.113178, 0.031777, 0.906857, 0.013068, 27.345812, 1.284633, 12.339972, 15.743898, 0.047385, 21.390038, 5.088041, 0.323969, 14.430306, 1.236607, 46.641335, 2305.140560, 0.243231, 4.332996, 14.797866, 0.247129, 3.616768, 1.527917, 53.360089, 0.269371, 9.797017, 3.893512, 0.388018, 38.573338, 9.828420, 0.238145)

# Names of the sequin for each data-point
ids <- c('GC_24_2','M11_G','M9_G','MG_22','MG_23','MG_24','MG_28','MG_3','MG_30','MG_32','MG_33','MG_34','MG_36','MG_37','MG_44','MG_46','MG_47','MG_50','MG_52','MG_53','MG_55','MG_57','MG_6','MG_60','MG_61','MG_62','MG_63','MG_68','MG_71','MG_8')

lx <- log2(x)
ly <- log2(y)
d  <- data.frame(x=lx, y=ly, ids=ids)

p <- ggplot(data = d, aes(x = x, y = y))
p <- p + xlab('Expected log2 fold change of mixture A and B')
p <- p + ylab('Measured log2 fold change of mixture A and B')
p <- p + geom_point()
p <- p + xlim(min(lx)-1, max(lx)+1)
p <- p + ylim(min(ly)-2, max(ly)+2)
p <- p + ggtitle("Plant growth with\ndifferent treatments")
p <- p + geom_smooth(method = "lm", formula = y ~ x)
p <- p + geom_text(x = min(d$x), y = max(d$y), label = lm_eqn(d), parse = TRUE)
print(p)

2 个答案:

答案 0 :(得分:2)

尝试:

 p + geom_text(x = 0, y = max(d$y), label = lm_eqn(d), parse = TRUE)

由于0,0中的原点是中间,x = 0将把它放在中间。

答案 1 :(得分:2)

更好地使用注释,否则多重标签重叠并且看起来模糊

  ggplot(data = d, aes(x = x, y = y)) + geom_point() + 
  annotate("text", x = -Inf, y = Inf, 
           label = lm_eqn(d), hjust = 0, vjust = 1, parse = TRUE)