Question adapted from this question and solution: Highlighting individual axis labels in bold using ggplot2
I would like to selectively justify the horizontal axes labels depending on meeting a criteria. So borrowing from the above question and answer I've set up an example:
require(ggplot2)
require(dplyr)
set.seed(36)
xx<-data.frame(YEAR=rep(c("X", "Y"), each=20),
CLONE=rep(c("A", "B", "C", "D", "E"), each=4, 2),
TREAT=rep(c("T1", "T2", "T3", "C"), 10),
VALUE=sample(c(1:10), 40, replace=T))
# Simple plot with factors on y axis
ggplot(xx, aes(x = VALUE, y=CLONE, fill=YEAR)) +
geom_bar(stat="identity", position="dodge") +
facet_wrap(~TREAT)
Ok so I adopted function from the above question + answer to generate a vector of justifications:
# Modify to control justification
colorado2 <- function(src, boulder) {
if (!is.factor(src)) src <- factor(src)
src_levels <- levels(src)
brave <- boulder %in% src_levels
if (all(brave)) {
b_pos <- purrr::map_int(boulder, ~which(.==src_levels))
b_vec <- rep(0.2, length(src_levels))
b_vec[b_pos] <- 0.9
b_vec
} else {
stop("All elements of 'boulder' must be in src")
}
}
# Redraw the plot with modifcation
ggplot(xx, aes(x = VALUE, y=CLONE, fill=YEAR)) +
geom_bar(stat="identity", position="dodge") +
facet_wrap(~TREAT) +
theme(axis.text.y=element_text(hjust=colorado2(xx$CLONE, c("A", "B", "E"))))
I'm getting this unfortunate mess:
The labels are justified in the direction I want - but taking up far too much of the plot for reasons I cannot figure out. How do I fix this ?
c("beer", "heineken", "guinness", "wine", "merlot", "chardonnay", "whiskey", "middelton","jameson")
and I want beer, wine and whiskey left justified and others right justified -they need to line up left or right – Hotchpot