rggplot2text-alignmentannotate

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.


Solution

  • hjust = 0 or hjust = "left" 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. You can also use hjust = "inward" or hjust = "outward" to align text in toward the center or out away from the center.

    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.

    Differences with GUI editors

    There's a bit of a difference in how text justification works in ggplot compared to how you may be used to in in a GUI document or slides editor. In those GUIs, you draw a textbox, and then you justify the text within that box--left justified goes to the left edge of the box, right justified goes to the right edge, and center in the middle.

    In ggplot, there is no text box. You specify a single point for the text, and the justification touches that. You may expect that if you change from left-justified to right-justified, the text will move to the right, but it will actually move to the left, as it is the right margin that is moving. This code illustrates:

    hjust_data = data.frame(z = paste("hjust =", c(0, 0.5, 1)))
    df = data.frame(x = 1:5, y = 1:5)
    df = merge(df, hjust_data, all = TRUE)
    
    text_df = subset(df, x == 3) |>
      transform(lab = "Your nice\nmultiple line text\nis here")
    
    ggplot(df, aes(x, y)) +
      geom_point() +
      facet_wrap(vars(z), ncol = 1) +
      geom_text(aes(label = lab), data = text_df[1, ], hjust = 0) +
      geom_text(aes(label = lab), data = text_df[2, ], hjust = 0.5) +
      geom_text(aes(label = lab), data = text_df[3, ], hjust = 1)
    

    enter image description here

    Comparison to base graphics

    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.