Skip to content

Instantly share code, notes, and snippets.

@SchmidtPaul
Last active February 21, 2022 09:38
Show Gist options
  • Save SchmidtPaul/290cdc394f5c29a5b6dfbe7c905d2fb0 to your computer and use it in GitHub Desktop.
Save SchmidtPaul/290cdc394f5c29a5b6dfbe7c905d2fb0 to your computer and use it in GitHub Desktop.
ggplot2: Positioning labels (or other geoms) on the outter sides when I only have two levels on my x-axis
library(tidyverse)
# data --------------------------------------------------------------------
dat <- tibble(
x = c("A", "A", "B", "B"),
y = c(12, 11, 13.03, 13),
grp = c("G1", "G2", "G1", "G2"),
lab = c("a", "abc", "ab", "abcd")
) %>%
mutate_if(is.character, as.factor)
# ggplot only -------------------------------------------------------------
ggplot(dat, aes(
x = x,
y = y,
label = lab,
group = grp
)) +
theme_classic() +
geom_point() +
geom_line() +
geom_text(aes(
x = if_else(as.integer(x) == 1, 0.9, 2.1),
hjust = if_else(as.integer(x) == 1, 1, 0)
))
# ggrepel -----------------------------------------------------------------
library(ggrepel)
ggplot(dat, aes(
x = x,
y = y,
label = lab,
group = grp
)) +
theme_classic() +
geom_point() +
geom_line() +
geom_text_repel(
data = subset(dat, as.integer(x) == 1),
nudge_x = -0.1, hjust = "right", direction = "y",
segment.linetype = "dotted",
segment.color = "darkgrey"
) +
geom_text_repel(
data = subset(dat, as.integer(x) == 2),
nudge_x = 0.1, hjust = "left", direction = "y",
segment.linetype = "dotted",
segment.color = "darkgrey"
)
@SchmidtPaul
Copy link
Author

ggplot only
ggonly

ggrepel
ggrepel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment