Does anyone know whether it’s possible to replicate in ggplot2 538’s feature of outlining text in a plot?
In the example attached. Would it be possible to add the rounded white outline to the percentage?
Does anyone know whether it’s possible to replicate in ggplot2 538’s feature of outlining text in a plot?
In the example attached. Would it be possible to add the rounded white outline to the percentage?
One option would be the shadowtext package and a second one would be ggrepel:
library(ggplot2)
library(shadowtext)
df <- data.frame(
x = factor(1),
y = factor(1),
label = "78%"
)
ggplot(df, aes(x = x, y = y, label = label)) +
geom_tile(fill = "firebrick") +
geom_shadowtext(color = "black", size = 14 / .pt, fontface = "bold", bg.colour = "white", bg.r = .2) +
theme_void()

library(ggrepel)
ggplot(df, aes(x = x, y = y, label = label)) +
geom_tile(fill = "firebrick") +
geom_text_repel(color = "black", size = 14 / .pt, fontface = "bold", bg.colour = "white", bg.r = .2, force = 0) +
theme_void()

You could simply use sprintf to add an underline under the label.
I've used Arthritis datset from vcd package to demonstrate this example.
Here's how you'll do it:
parseLabel <- sprintf("underline(%s)~\n~%s",
gsub(" ", "~", df$Treatment, fixed = TRUE),
gsub(" ", "~", length(df$Treatment), fixed = TRUE))
p <- ggplot(df, aes(x = Treatment)) +
geom_histogram(stat = "count") +
stat_count(geom = "text", color = "white", size = 3.5,
aes(label = parseLabel), position = position_stack(vjust = 0.5), parse = T)
p + theme_fivethirtyeight()