Emilio M. Bruna
Emilio M. Bruna

Reputation: 359

Change name of point labels in

I know how to add point labels when using ggplot2 using geom_text()

p <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))
p + geom_text()

enter image description here

But what if I want to change "Fiat X1-9" to "WORST CAR EVER" without changing the entries in the original dataframe? Is there a way to rename the point in the plot within geom_text()?

Thanks much.

Upvotes: 0

Views: 1770

Answers (1)

Pierre L
Pierre L

Reputation: 28461

You can override the aesthetic or use it in the initial expression:

nms <- rownames(mtcars)
p + geom_text(aes(label = replace(nms, nms == "Fiat X1-9", "Worst Car Ever")))

Edit

If you do not want to create a new object you can use this. But as a point of advice, don't become too attached to one-liners. They are fun, but sometimes creating an object is the best for readability, debugging, and accuracy.

p + geom_text(aes(label = replace(rownames(mtcars), rownames(mtcars) == "Fiat X1-9", "Worst Car Ever")))

Upvotes: 1

Related Questions