我希望将文本放置在ggplot
中,而不指定x
和y
位置,而是使用关键字,例如在graphics::legend
中(“位置也可以通过从列表”“右下角”、“底部”、“左下角”、“左”、"topleft“、”顶上“、”右上“、”右“和”中间“中的单个关键字来指定)。
让我说我在做这样的图表。
sp <- ggplot(mpg, aes(hwy, cty, label = "sometext")) +
geom_point()
我想添加标签,以同样的方式打印在每一个图表。调用以下内容只需在每个x
上打印文本,y
值就可以提供给aes
。
sp + geom_text()
我可以操作提供给x
和y
的geom_text()
数据,以确保文本在图形之间保持相同的相对位置,但难道没有一种简单的方法在默认情况下调用"top"
、"bottom"
等位置吗?即sp + geom_text(position = "top")
.
发布于 2017-12-21 00:44:59
geom_text
希望根据您的数据集绘制标签。听起来你想在你的情节中添加一个文本,在这种情况下,annotate
是更好的选择。要强制标签出现在相同的位置,而不管绘图中的单元是什么,您可以利用Inf
值:
sp <- ggplot(mpg, aes(hwy, cty, label = "sometext"))+
geom_point() +
annotate(geom = 'text', label = 'sometext', x = -Inf, y = Inf, hjust = 0, vjust = 1)
print(sp)
发布于 2017-12-21 03:02:57
我避免像瘟疫一样使用annotate
,只需为geom_text
使用一个空的数据帧data
参数。
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)
发布于 2020-07-10 21:16:10
在ggpmisc::geom_text_npc
中,x
和y
的位置以npc单位(0-1)表示.但是,这些立场也可指定为“词语”:
d = data.frame(x = rep(c("left", "center", "right"), each = 3),
y = rep(c("bottom", "middle", "top"), 3))
d$lab = with(d, paste0(x, "-", y))
d
# x y lab
# 1 left bottom left-bottom
# 2 left middle left-middle
# 3 left top left-top
# 4 center bottom center-bottom
# 5 center middle center-middle
# 6 center top center-top
# 7 right bottom right-bottom
# 8 right middle right-middle
# 9 right top right-top
ggplot(d) +
geom_text_npc(aes(npcx = x.chr, npcy = y.chr, label = lab))
https://stackoverflow.com/questions/47916307
复制相似问题