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
245 views
in Technique[技术] by (71.8m points)

r - How to make geom_text plot within the canvas's bounds

Using geom_text to label outlying points of scatter plot. By definition, these points tend to be close to the canvas edges: there is usually at least one word that overlaps the canvas edge, rendering it useless.

Clearly this can be solved manually in the case below using + xlim(c(1.5, 4.5)):

# test
df <- data.frame(word = c("bicycle", "tricycle", "quadricycle"),
                 n.wheels = c(2,3,4),
                 utility = c(10,6,7))
ggplot(data=df, aes(x=n.wheels, y=utility, label=word))  + geom_text() + xlim(c(1.5, 4.5))

trike

This is not ideal though, as

  1. It's not automated, so slows down the process if many plots are to be produced
  2. It's not accurate, meaning the distance between the edge of the word and the edge of the canvas is not equal in every case.

Searches for this problem reveal no solutions, and Hadley Wickham seems to be content with labels being cut in half in ggplot2's help page (I know Hadley, they're just an examples ;)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

ggplot 2.0.0 introduced new options for hjust and vjust for geom_text() that may help with clipping, especially "inward". We could do:

ggplot(data=df, aes(x=n.wheels, y=utility, label=word))  + 
  geom_text(vjust="inward",hjust="inward")

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

...