Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left align text in annotate from ggplot2

My example is:

qplot(mtcars$mpg) + 
  annotate(geom = "text", x = 30, y = 3, label = "Some text\nSome more text")

How do I get the text here to be left aligned? So that the 'Some's line up with each other.

like image 723
kennyB Avatar asked Oct 31 '14 21:10

kennyB


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.

Which justification flushes text with the left and right margin?

When you justify text in Word, you give your text straight edges on both sides of the paragraph. Justifying extends each line of your text to the left and right margins.


1 Answers

hjust = 0 does what you want. hjust stands for horizontal justification, 0 will be left-justified, 0.5 will be centered, and 1 will be right-justified.

qplot(mtcars$mpg) +
    annotate(geom = "text", x = 30, y = 3,
             label = "Some text\nSome more text",
             hjust = 0)

See also vjust for vertical justification.

In ggplot2, these arguments are present any time text preferences are set. They work for annotate, geom_text, or in element_text when adjusting theme options.

If you look at ?geom_text, you can find text string options: "left", "middle", or "right", (for hjust), "top", "center", "bottom" for vjust, and for either "inward" and "outward" which will always adjust in toward or out away from the center.


This behavior is similar in many base graphics functions, such as the adj argument for par, used by text(), mtext(), and title(), which can be vector of length 2 for the horizontal and vertical justificatons. Also the hadj and padj arguments to axis() for justifications horizontal to and perpendicular to the axis.

like image 71
Gregor Thomas Avatar answered Oct 22 '22 19:10

Gregor Thomas