Emilio M. Bruna Emilio M. Bruna - 2 months ago 8
R Question

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.

Answer

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")))
Comments