2

Im trying to label only one facet in my plot...

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + annotate("text", label = "Test", size = 4, x = 15, y = 5)
print(p)

example

when I try the suggested fix on another post Annotating text on individual facet in ggplot2 , it does not work....

ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",
                   cyl = factor(8,levels = c("4","6","8")))
p + geom_text(data = ann_text,label = "Text")

example 2

any sugestions?

Eliott Reed
  • 351
  • 1
  • 4
  • 12
  • 5
    just don't run the `p + annotate` line – rawr Jan 26 '20 at 04:15
  • The line: "cyl = factor(8,levels = c("4","6","8")))" should be the factor that has been faceted. However, when I apply it to my data i get an error message saying the object does not exist. – Eliott Reed Jan 27 '20 at 02:18

2 Answers2

2

The most reliable way that worked for me in the past was to create a new data frame, with the the facet variable containing only one value, as shown below.

library(tidyverse)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + geom_text(data = data.frame(x = 15, y = 5, cyl = 4, label = "Test"), 
                   aes(x = x, y = y, label = label), size = 4)
print(p)

This will generate:

enter image description here

Seshadri
  • 669
  • 3
  • 11
0

The correct version based on the suggested fix provided above should be as follows:

ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text", cyl = factor(8,levels = c("4","6","8"))) p + geom_text(data = ann_text,label = ann_text$lab)

It should be label=ann_text$lab, instead of label="Text.

Ye Li
  • 1
  • 1