I built a Shiny application with multiple ggplot2 graphs of Social Security trust fund valuation metrics for a project. The plot titles are currently left-aligned with the left edge of the Cartesian coordinate plane. This doesn't fit our style guide.
In a static (non-Shiny) ggplot2 graph, I can use theme(plot.title = element_text(hjust = -0.24)
to align the title with the left edge of the y-axis labels. In the Shiny application, the y-axis labels change and the length can be $100, $1,000, $10,000, etc. depending upon selections in the application. Is there a way to left-justify titles and subtitles to the left edge of the longest y-axis label other than guessing-and-checking with hjust = -x.x
?
An example:
library(tidyverse)
ggplot(diamonds, aes(carat, price)) +
geom_point() +
labs(title = "Diamonds",
subtitle = "Bigger Dimaonds Cost More Money") +
theme(plot.title = element_text(hjust = 0)) +
ylab(NULL) +
scale_y_continuous(expand = c(0,0), labels = dollar) +
theme(plot.title = element_text(hjust = -0.24),
plot.subtitle = element_text(hjust = -0.57))
The title above is correctly aligned. Below, the length of the y-axis labels change and now the title is misaligned.
library(tidyverse)
diamonds %>%
filter(price < 10000) %>%
ggplot(aes(carat, price)) +
geom_point() +
labs(title = "Diamonds",
subtitle = "Bigger Dimaonds Cost More Money") +
theme(plot.title = element_text(hjust = 0)) +
ylab(NULL) +
scale_y_continuous(expand = c(0,0), labels = dollar) +
theme(plot.title = element_text(hjust = -0.24),
plot.subtitle = element_text(hjust = -0.58))
I found a lot of Stack Overflow posts from before ggplot2 2.2.0 when users wanted to left-align the title instead of using the default centered title. There is also a solution for titles using textGrob()
from grid and arrangeGrob()
from gridExtra, but I have been unable to exapnd this solution to the subtitle.
I haven't found a solution to this problem. Also, I would have included informative images but I do not have 10 reputation. Thank you in advance!