I\'m working on a chart similar to a slopegraph, where I\'d like to put labels along one or both sides with ample blank space to fit them on both sides. In cases where label
TL;DR: probably a bug
Long answer:
I think it might be a bug in the code. I checked the gtable of the plot you made, wherein the hjust
was specified numerically and correctly:
# Assume 'g' is the plot saved under the variable 'g'
gt <- ggplotGrob(g)
# Your number at the end of the geom may vary
textgrob <- gt$grobs[[6]]$children$geom_text_repel.textrepeltree.1578
head(textgrob$data$hjust)
[1] 1 0 1 0 1 0
Which got me thinking that (1) the plot can't be fixed by messing around in the gtable and (2) the drawtime code for the textrepeltree
class of grobs may contain some errors. This makes sense, since the labels are repositioned when the plot device is resized. So when we look at the makeContent.textrepeltree()
code in the link you provided, we can see that the hjust
parameter is passed on to makeTextRepelGrobs()
. Let's have a look at the relevant formals:
makeTextRepelGrobs <- function(
...other_arguments...,
just = "center",
...other_arguments...,
hjust = 0.5,
vjust = 0.5
) { ...body...}
We can see that hjust
is a valid argument, but there also exists a just
argument, which is an argument that is not passed on from makeContent.textrepeltree()
.
When we look at the function body there are these two lines:
hj <- resolveHJust(just, NULL)
vj <- resolveVJust(just, NULL)
Where resolveH/VJust
are imported from the grid package. The resolveHJust()
essentially checks whether the second argument is NULL
and if that is true, default to the first argument, otherwise return the second argument. You can see that the hjust
that was passed on to makeTextRepelGrobs()
does not get passed to resolveHJust()
, and this seems to be the point where your hjust
parameter is dropped unexpectedly.
Further down the code is where the actual text grobs are made:
t <- textGrob(
...other_arguments...
just = c(hj, vj),
...other_arguments...
)
I imagine that the fix would be relatively straightforward: you would just have to supply hjust
as the second argument to resolveHJust()
. However, since that makeTextRepelGrobs()
is internal to ggrepel and does not get exported, you would have to copy a lot of extra code to get this to work. (Not sure if only copying the makeTextRepelGrob()
would be sufficient, haven't tested this)
All of this leaves me to conclude that the hjust
that you specified in geom_text_repel()
gets lost at the last moment of drawtime by the makeTextRepelGrobs()
internal function.