Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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), "\n Median =",           round(MyMedian, 1), "\n 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.

like image 590
ATMathew Avatar asked Aug 10 '10 21:08

ATMathew


People also ask

How do you left align text in R?

Left alignment can be requested by setting sep = "\\l" , right alignment by "\\r" and center alignment by "\\c" . Mind the backslashes, as if they are omitted, strings would be aligned to the character l, r or c respectively. Default value is "\\r" , thus right alignment.


2 Answers

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.

For left justified replace your text code with...

text(1.5, 150, paste("Mean =", round(MyMean, 1), "\nMedian =",           round(MyMedian, 1), "\nStd.Dev =", round(MySd, 1)), pos = 4) 

and for right justified...

text(5.0, 150, paste("Mean = ", round(MyMean, 1), "\nMedian = ",          round(MyMedian, 1), "\nStd.Dev = ", round(MySd, 1), sep = ''), pos = 2) 
like image 120
John Avatar answered Oct 05 '22 05:10

John


Try using legend() instead of text()

legend(3.5, 150, legend = c(paste("Mean =", round(MyMean, 1)),                             paste("Median =",round(MyMedian, 1)),                             paste("Std.Dev =", round(MySd, 1))),                    bty = "n") 

You'll have to play around with the position adjustment. You might consider not using xy coordinates at all, but replacing those two arguments with "topleft"

like image 43
JoFrhwld Avatar answered Oct 05 '22 04:10

JoFrhwld