3

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?

enter image description here

camille
  • 16,432
  • 18
  • 38
  • 60
PabloAB
  • 233
  • 1
  • 6
  • Related post: [How to combine repelling labels and shadow or halo text in ggplot2?](https://stackoverflow.com/questions/56798482/how-to-combine-repelling-labels-and-shadow-or-halo-text-in-ggplot2) – stefan Dec 30 '21 at 10:17

2 Answers2

5

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()

stefan
  • 90,330
  • 6
  • 25
  • 51
  • 1
    Didn't know either shadowtext or this particular ggrepel feature. Neat. Learning point of the day :) – tjebo Dec 30 '21 at 13:16
0

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()

The output looks like this: enter image description here

Vishal A.
  • 1,373
  • 8
  • 19