I have multi-line x-axis labels, which I want left-adjusted within the label (so that the left side of both lines is at the same indentation), but centrally positioned under the axis tick. if I use theme(axis.text = element_text(hjust = 0)), the text lines are properly indented to the same level, but positioned to the right of the tick (see MWE). how do I get them positioned centrally under the tick?
library(ggplot2)
library(stringr)
## Create a sample data frame
df <- data.frame(x = 1:5,
y = c(2, 4, 3, 5, 6),
label = c("Line 1 Label", "Line 2 Label is a bit longer",
"Line 3 Label is even longer than the previous one",
"Line 4 Label is not so long", "Line 5 Label"))
## Wrap the label text with str_wrap()
df$label <- str_wrap(df$label, width = 15)
## Create the plot
ggplot(df, aes(x, y)) +
geom_point() +
scale_x_continuous(breaks = 1:5, labels = df$label) +
theme(axis.text.x = element_text(hjust = 0))
One option would be to use ggtext::element_markdown
which besides hjust
to align the overall bounding box of the axis text has an additional argument halign
to align the axis text inside the box, i.e. we could use hjust=.5
to center the box and use halign=0
to left-justify the text:
library(ggtext)
library(ggplot2)
library(stringr)
## Create a sample data frame
df <- data.frame(
x = 1:5,
y = c(2, 4, 3, 5, 6),
label = c(
"Line 1 Label", "Line 2 Label is a bit longer",
"Line 3 Label is even longer than the previous one",
"Line 4 Label is not so long", "Line 5 Label"
)
)
df$label <- str_wrap(df$label, width = 15)
df$label <- str_replace_all(df$label, "\\n", "<br>")
ggplot(df, aes(x, y)) +
geom_point() +
scale_x_continuous(breaks = 1:5, labels = df$label) +
theme(axis.text.x = ggtext::element_markdown(hjust = .5, halign = 0))