I often find myself wanting to align the x-axis labels on my plots differently based on their location, with values on the left left-aligned and values on the right, right-aligned. However, element_text
doesn't have official support for vectorized input (and never will?) so I'm wondering how to solve this in proper ggplot2
fashion.
The problem: overlapping x-axis labels (and truncated on the far right)
library(ggplot2)
v <- data.frame(x=1:2, y=1:2, facet=gl(2, 2))
gp <- ggplot(v) +
geom_point(aes(x=x, y=y)) +
scale_x_continuous(breaks = 1:2, labels = c("Minimum", "Maximum")) +
facet_wrap(~facet)
gp
My solution:
gp + theme(axis.text.x = element_text(hjust=c(0, 1)))
Except:
Warning message:
Vectorized input to `element_text()` is not officially supported.
ℹ Results may be unexpected or may change in future versions of ggplot2.
What's the correct way to differently-align text in a ggplot if vectorized element_text
isn't supported?
Claus Wilke states here that his ggtext package does support the use of vectors in this way and it will continue supporting it in the future. As thomasp85 (Thomas Lin Pedersen) says in the thread "FWIW, I think most of the use cases for this hack can be solved properly using element_markdown()", i.e.
library(ggplot2)
library(ggtext)
v <- data.frame(x=1:2, y=1:2, facet=gl(2, 2))
gp <- ggplot(v) +
geom_point(aes(x=x, y=y)) +
scale_x_continuous(breaks = 1:2, labels = c("Minimum", "Maximum")) +
facet_wrap(~facet)
gp
gp +
theme(axis.text.x = element_markdown(hjust = c(0, 1)))
Created on 2023-04-11 with reprex v2.0.2