Closed
Description
The problem
Text labels can be displayed in an unexpected order if you use parse = TRUE
:
library(ggplot2)
library(patchwork)
d <- data.frame(
x = c(1, 2, 3),
y = c(1, 0, 1),
label = c("alpha", "", "gamma")
)
p <- ggplot(d, aes(x = x, y = y, label = label)) + geom_point(color = "red")
p1 <- p + geom_text(size = 5, parse = FALSE) + labs(title = "Good :)")
p2 <- p + geom_text(size = 5, parse = TRUE) + labs(title = "Bad :(")
ggsave(filename = "issue.png", plot = p1 + p2, width = 4, height = 2)
The culprit: parse() drops empty strings
To my surprise, the parse()
function silently drops the empty string:
x <- c("alpha", "", "gamma")
x
#> [1] "alpha" "" "gamma"
length(x)
#> [1] 3
y <- parse(text = x)
y
#> expression(alpha, gamma)
length(y)
#> [1] 2
c(expression(alpha), expression(), expression(gamma))
#> expression(alpha, gamma)
Unfortunately, I don't know how to deal with this. Do you have any ideas?
A workaround
One workaround is to create a second dataframe just for the text labels. That way, you can avoid passing an empty string to the parse()
function.
d2 <- d[d$label != "",]
p3 <- p + geom_text(size = 5, parse = TRUE, data = d2) + labs(title = "Yay :)")
ggsave(filename = "workaround.png", plot = p1 + p3, width = 4, height = 2)
Related issues
@pakidermo5000 originally reported this here: slowkow/ggrepel#114
Metadata
Metadata
Assignees
Labels
No labels