我在ggplot中制作了一些图表,无法弄清楚如何在不指定x和y位置的情况下绘制图形文本。
可以说我正在制作这样的图表。
sp <- ggplot(mpg, aes(hwy, cty, label = "sometext"))+
geom_point()
我想在每个图表中以相同的方式添加要打印的标签。调用以下内容只需在提供给aes
的每个x,y值处打印文本。
sp + geom_text()
我可以操纵提供给geom_text()
的x y数据,以确保文本保持在图形之间的相同相对位置,但是没有一种简单的方法来调用默认位置,如“顶部”,“底部”等?即sp + geom_text(position="top")
。
我像瘟疫一样避免使用annotate
,只使用data
的空数据框geom_text
参数:
ggplot(mpg, aes(hwy, cty, label = "sometext"))+
geom_point() +
geom_text(data=data.frame(), aes(label = 'sometext', x = -Inf, y = Inf),
hjust = 0, vjust = 1)
使用无穷大的解决方案很好,绝对是最简单的选择。
但是,如果您想要更多地控制标签的位置(例如,如果您希望它们居中,或者您希望轴线和注释之间有更多空间),您可以使用一些数学与min()
和max()
的情节标题在顶部,底部,右侧或左侧创建居中的标题。下面的代码有点冗长,但如果绘图中的值发生变化,仍会正确放置标签。此外,要复制到其他绘图,您不需要手动计算值,只需更改x和y变量的名称。
sp <- ggplot(mpg, aes(hwy, cty)) +
geom_point() +
theme_classic() +
annotate("text", label = "top",
x = 0.5*(min(mpg$hwy) + max(mpg$hwy)), y = max(mpg$cty), vjust = 1) +
annotate("text", label = "bottom",
x = 0.5*(min(mpg$hwy) + max(mpg$hwy)), y = min(mpg$cty), vjust = 0) +
annotate("text", label = "right",
x = max(mpg$hwy), y = 0.5*(min(mpg$cty) + max(mpg$cty)), hjust = 1) +
annotate("text", label = "left",
x = min(mpg$hwy), y = 0.5*(min(mpg$cty) + max(mpg$cty)), hjust = 0)
sp
编写包装器当然是可能的,但单元和对齐的定义方式使它相当冗长,
library(ggplot2)
qplot(1,1) +
annotation_compass('testN') +
annotation_compass('testE','E') +
annotation_compass('testSW','SW') +
annotation_compass('testW','W')
annotation_compass <- function(label,
position = c('N','NE','E','SE','S','SW','W','NW'),
padding = grid::unit(c(0.5,0.5),"line"), ...){
position <- match.arg(position)
x <- switch (position,
N = 0.5,
NE = 1,
E = 1,
SE = 1,
S = 0.5,
SW = 0,
W = 0,
NW = 0
)
y <- switch (position,
N = 1,
NE = 1,
E = 0.5,
SE = 0,
S = 0,
SW = 0,
W = 0.5,
NW = 1
)
hjust <- switch (position,
N = 0.5,
NE = 1,
E = 1,
SE = 1,
S = 0.5,
SW = 0,
W = 0,
NW = 0
)
vjust <- switch (position,
N = 1,
NE = 1,
E = 0.5,
SE = 0,
S = 0,
SW = 0,
W = 0.5,
NW = 1
)
f1 <- switch (position,
N = 0,
NE = -1,
E = -1,
SE = -1,
S = 0,
SW = 1,
W = 1,
NW = 1
)
f2 <- switch (position,
N = -1,
NE = -1,
E = 0,
SE = 1,
S = 1,
SW = 1,
W = 0,
NW = -1
)
annotation_custom(grid::textGrob(label,
x=grid::unit(x,"npc") + f1*padding[1] ,
y=grid::unit(y,"npc") + f2*padding[2],
hjust=hjust,vjust=vjust, ...))
}