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

r - Align text inside a plot

I am an R newbie and had a question. I am trying to place some text into an R plot. Here's some code using the brightness dataset in the UsingR package.

    library(UsingR)
    brightness

    MyMean <- mean(brightness)
    MyMedian <- median(brightness)
    MySd <- sd(brightness)

    hist(brightness, breaks=35, main="This is a Histogram", 
         xlab="Brightness", ylab="Frequency", xlim=c(0,15), ylim=c(0, 200))

    text(3.5, 150, paste("Mean =", round(MyMean, 1), "
 Median =", 
         round(MyMedian, 1), "
 Std.Dev =", round(MySd, 1)))

This code produces:

enter image description here

The issue with this output is that the text is not left left alligned. Does anyone know how to make the text left alligned.

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

While legend() is of course appropriate for legends, there is a general solution for all text. The trick is that the pos option not only sets the position of the text relative to the current location but it also sets justification. Above and Below are center justified. Setting pos to 2 makes the text right justified. When it is set to the right of the position (pos?=?4) then it is left justified.

Replace your text code with...

text(1.5, 150, paste("Mean =", round(MyMean, 1), "
Median =", 
         round(MyMedian, 1), "
Std.Dev =", round(MySd, 1)), pos = 4)

for left justified and...

text(5.0, 150, paste("Mean = ", round(MyMean, 1), "
Median = ", 
        round(MyMedian, 1), "
Std.Dev = ", round(MySd, 1), sep = ''), pos = 2)

for right justified.


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

...