0

I am trying to label facets with text, but they are overlapping in each Facet instead of just showing one by one. This is the code I have been using:

ggplot(df) +
    aes(x = xvalues, y = yvalues) +
    geom_point(size = 1, shape = 1) +
    facet_wrap(~ model_f, ncol = 3) +
    geom_text(data = df2, aes(x = 33, y = 2.2, label = test), 
              parse = TRUE, check_overlap = FALSE)

So with my data I should have 6 plots (plotted according to the model_f column I have in my data), which I get. But when I try to use the geom_text function with the data frame:

df2 <- data.frame(test = c("one", "two", "three", "four", "five", "six"))

Each facet plot gets all strings, but on top of each other. If I use the check_overlap = TRUE function I just get the first element in each Facet, which is "one".

How do you make the text labels show on each facet individually?

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
Denver Dang
  • 2,433
  • 3
  • 38
  • 68

1 Answers1

3

If you create a dataframe for adding labels, this data must also have a column for the facet data. Using the iris dataset as an example:

label_text  <- data.frame(lab=c("Label 1","Label 2","Label 3"),
                          Species = levels(iris$Species))

Creates the following dataframe:

      lab    Species
1 Label 1     setosa
2 Label 2 versicolor
3 Label 3  virginica

We can then plot the graph:

ggplot(iris) +
  aes(x = Sepal.Length, y = Sepal.Width) +
  geom_point(size = 1, shape = 1, aes(col = Species)) +
  facet_wrap(~ Species, ncol = 3) +
  geom_text(data = label_text, x = 6.2, y = Inf, aes(label = lab), vjust = 2)

enter image description here

To vary the position of the label on the plot, you can alter the x and y coordinates in the label geom_text argument.

Alternative Approach

Rather than adding the label to the plot, you can alter the facet name before you plot the graph:

# First we merge the label data as a column to the full dataset
df <- merge(iris, label_text, by = "Species")

# Then we create our label name
df$facet <- paste0(df$Species, "\n (stat = ", df$lab, ")")

# Plot the results
ggplot(df) +
  aes(x = Sepal.Length, y = Sepal.Width) +
  geom_point(size = 1, shape = 1, aes(col = Species)) +
  facet_wrap(~ facet, ncol = 3) + 
  theme(legend.position = "none")

enter image description here

I personally prefer the second technique, as you haven't got to worry about manually specifying coordinates.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84