Text annotations

Add text annotations to a plot using geom_text and geom_label.

library(ggplot2)
library(canvasXpress)
p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars)))
e <- p + geom_text()
e
canvasXpress(e)

# Avoid overlaps
e <- p + geom_text(check_overlap = TRUE)
e
canvasXpress(e)

# Labels with background
e <- p + geom_label()
e
canvasXpress(e)

# Change size of the label
e <- p + geom_text(size = 10)
e
canvasXpress(e)

# Set aesthetics to fixed value
e <- p +
  geom_point() +
  geom_text(hjust = 0, nudge_x = 0.05)
e
canvasXpress(e)

e <- p +
  geom_point() +
  geom_text(vjust = 0, nudge_y = 0.5)
e
canvasXpress(e)

e <- p +
  geom_point() +
  geom_text(angle = 45)
e
canvasXpress(e)

# Add aesthetic mappings
e <- p + geom_text(aes(colour = factor(cyl)))
e
canvasXpress(e)

e <- p + geom_text(aes(colour = factor(cyl))) +
  scale_colour_hue(l = 40)
e
canvasXpress(e)

e <- p + geom_label(aes(fill = factor(cyl)), colour = "white", fontface = "bold")
e
canvasXpress(e)

# You can display expressions by setting parse = TRUE.  The
# details of the display are described in ?plotmath, but note that
# geom_text uses strings, not expressions.
e <- p +
  geom_text(
    aes(label = paste(wt, "^(", cyl, ")", sep = "")),
    parse = TRUE
  )
e
canvasXpress(e)

# Add a text annotation
e <- p +
  geom_text() +
  annotate(
    "text", label = "plot mpg vs. wt",
    x = 2, y = 15, size = 8, colour = "red"
  )
e
canvasXpress(e)

# \donttest{
# Aligning labels and bars --------------------------------------------------
df <- data.frame(
  x = factor(c(1, 1, 2, 2)),
  y = c(1, 3, 2, 1),
  grp = c("a", "b", "a", "b")
)
# ggplot2 doesn't know you want to give the labels the same virtual width
# as the bars:
e <- ggplot(data = df, aes(x, y, group = grp)) +
  geom_col(aes(fill = grp), position = "dodge") +
  geom_text(aes(label = y), position = "dodge")
e
canvasXpress(e)

# So tell it:
e <- ggplot(data = df, aes(x, y, group = grp)) +
  geom_col(aes(fill = grp), position = "dodge") +
  geom_text(aes(label = y), position = position_dodge(0.9))
e
canvasXpress(e)

# You can't nudge and dodge text, so instead adjust the y position
e <- ggplot(data = df, aes(x, y, group = grp)) +
  geom_col(aes(fill = grp), position = "dodge") +
  geom_text(
    aes(label = y, y = y + 0.05),
    position = position_dodge(0.9),
    vjust = 0
  )
e
canvasXpress(e)

# To place text in the middle of each bar in a stacked barplot, you
# need to set the vjust parameter of position_stack()
e <- ggplot(data = df, aes(x, y, group = grp)) +
 geom_col(aes(fill = grp)) +
 geom_text(aes(label = y), position = position_stack(vjust = 0.5))
e
canvasXpress(e)