Eliott Reed
Eliott Reed

Reputation: 321

How to label only one facet in ggplot

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?

Upvotes: 2

Views: 3997

Answers (2)

Ye Li
Ye Li

Reputation: 1

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.

Upvotes: 0

Seshadri
Seshadri

Reputation: 679

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

Upvotes: 2

Related Questions