Is there a way to add labels to each point in a plot? I did this on an image editor just to convey the idea: 1.
The original one was generated with:
qplot(pcomments, gcomments , data = topbtw, colour = username)
Click the chart, and then click the Chart Design tab. Click Add Chart Element and select Data Labels, and then select a location for the data label option. Note: The options will differ depending on your chart type. If you want to show your data label inside a text bubble shape, click Data Callout.
Import the library. Create the function which can add the value labels by taking x and y as a parameter, now in the function, we will run the for loop for the length of the x value we can find the length by using the len() function, and in that passed variable whose length we want. Now use plt.
To follow up on Andrie's excellent answer, I frequently employ two methods to add labels to a subset of points on a plot if I need to highlight specific data. Both are demonstrated below:
dat <- data.frame(x = rnorm(10), y = rnorm(10), label = letters[1:10]) #Create a subset of data that you want to label. Here we label points a - e labeled.dat <- dat[dat$label %in% letters[1:5] ,] ggplot(dat, aes(x,y)) + geom_point() + geom_text(data = labeled.dat, aes(x,y, label = label), hjust = 2) #Or add a separate layer for each point you want to label. ggplot(dat, aes(x,y)) + geom_point() + geom_text(data = dat[dat$label == "c" ,], aes(x,y, label = label), hjust = 2) + geom_text(data = dat[dat$label == "g" ,], aes(x,y, label = label), hjust = 2)
Yes, use geom_text() to add text to your plot. Here is an example:
library(ggplot2) qplot(mtcars$wt, mtcars$mpg, label=rownames(mtcars), geom="text") ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars))) + geom_text(size=3)
See the on-line documentation for more information: http://had.co.nz/ggplot2/geom_text.html
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