Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (7.3k points)
edited by

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.

2 Answers

0 votes
by

To left-align text in annotate function, you can use the hjust argument that is used to control the horizontal justification, 0 means left-justified, 0.5 means centered, and 1 means right-justified.

In your case:

qplot(mtcars$mpg) +

  annotate(geom = "text", x = 30, y = 3,

           label = "Some text\nSome more text",

           hjust = 0)

Output:

image

0 votes
by (1.8k points)

For text alignment in the annotate() function in ggplot2 can be handled by using hjust that stands for horizontal justification. It is whereby the value of hjust determines the position of the actual text concerning the mentioned co-ordinates.

 More precisely, when hjust values is zero the text is left-aligned, when hjust is equal to 0.5 – the text is centered, and when hjust is set to 1 – the text is right-aligned. 

In your case for instance you wish to align the text to the left you can use hjust = 0. 

For example, you could write the following code:

qplot(mtcars$mpg) + 

  annotate(geom = "text", x = 30, y = 3, 

           label = "Some text\nSome more text", 

           hjust = 0)

Besides, the hjust = 0 in this code will mean that the text box will be aligned to the left of the given x and y coordinates. The newline character (\n) makes the text go to the next line, and the methods of left alignment will make the start of the text go right to where the position is wanted for a nice and neat looking text that is aligned.

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...