Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

r - Specify position of geom_text by keywords like "top", "bottom", "left", "right", "center"

I wish to position text in a ggplot without specifying x and y positions, but instead using keywords, like e.g. in graphics::legend ("The location may also be specified by setting x to a single keyword from the list "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center").

Lets say I'm making a graph like this.

sp <- ggplot(mpg, aes(hwy, cty, label = "sometext")) +
       geom_point()

I want to add the label to be printed in the same way in every graph. Calling the following simply prints text at every x, y value supplied to aes.

sp + geom_text()

I could manipulate the x and y data supplied to geom_text() to ensure that the text remained in the same relative position between graphs, but is there not a simply way to call position by default positions like "top", "bottom" etc? I.e. sp + geom_text(position = "top").

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

geom_text wants to plot labels based on your data set. It sounds like you're looking to add a single piece of text to your plot, in which case, annotate is the better option. To force the label to appear in the same position regardless of the units in the plot, you can take advantage of Inf values:

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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...