Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add labels to a plot

Tags:

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)

Manually added fake labels to qplot

like image 827
amh Avatar asked Apr 03 '11 08:04

amh


People also ask

How do you add labels to a plot?

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.

How do you add data labels to a plot in Python?

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.


2 Answers

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) 
like image 107
Chase Avatar answered Sep 20 '22 16:09

Chase


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

enter image description here

like image 38
Andrie Avatar answered Sep 20 '22 16:09

Andrie