With this code:
library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point() p + geom_point() + geom_text(aes(wt, mpg, label=row.names(mtcars)))
I obtain this graph:
How can I modify the code above so that it only labels point where wt > 4
or mpg > 25
, while the rest of the points remain unlabeled.
To add labels at specified points use annotate() with annotate(geom = "text", ...) or annotate(geom = "label", ...) . To automatically position non-overlapping text labels see the ggrepel package.
The function geom_point() adds a layer of points to your plot, which creates a scatterplot.
Use the title( ) function to add labels to a plot. Many other graphical parameters (such as text size, font, rotation, and color) can also be specified in the title( ) function. # labels 25% smaller than the default and green.
To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .
Supply a data
argument to geom_text
:
library(ggplot2) mtcars$name <- row.names(mtcars) p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point() p + geom_point() + geom_text(data=subset(mtcars, wt > 4 | mpg > 25), aes(wt,mpg,label=name))
Resulting plot:
PS: I'm really not a fan of the p + geom()
style of constructing ggplots, I'm pretty sure hadley did it in the original ggplot2 book to demonstrate different modifications of the same plot, but people seem to have picked it up and run with it. Here's how I'd do it:
+
, don't save each intermediate step.ggsave()
ggplot
call, only modify the other things if necessaryMy version:
ggplot(mtcars, aes(wt, mpg, label=name)) + geom_point() + geom_text(data=subset(mtcars, wt > 4 | mpg > 25))
You can pass a subset
argument to a layer. In your case this would require having the rownames as a column, so they are evaluated properly. You will need to explicitly load plyr
to get the function .
which makes the syntax easy.
# shamelessly using @marius initial code library(ggplot2) library(plyr) mtcars$name <- row.names(mtcars) p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point() + geom_text(aes(wt,mpg,label=name), subset = .(wt > 4 | mpg > 25))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With