R - how to use contents of one vector as the symbol in a plot?

This should work:

x = 1:4
y = x
plot(x, y, ann=F, axis=F, col="blue", pch=16)
text(x, y, labels=c("1st", "2nd", "3rd", "4th"), col="red", pos=c(3,4,4,1), offset=0.6)

Just convert your non-data vector (the one containing the labels) to a character vector: labels = as.character(label_vector)

and then substitute this for the third argument in line 4 above.

The 'Text' function is fairly versatile because of the various arguments you can pass in--e.g., (as in the example above) you can set the text to a different color than your data points using "col"; You can also specify the position (relative to the data point annotated by a given text label) for each text label separately. That's often useful to keep text labels from, for instance, overlapping one of the axes, which is what happened the first time i ran this example without setting 'pos'. So by setting 'pos' (as c(3, 4, 4, 1)) i set the position of the text labels as "above", "right", "right", and "below"--moving the first data point up so it doesn't hit the bottom x-axis, and moving the fourth one down so it doesn't hit the top x-axis. Additionally, using 'offset' (which has a default value of 0.5) you can specify the magnitude of the position adjustment.


Here is a way to do this using the ggplot2 package:

library(ggplot2)
x <- rnorm(10)
y <- rnorm(10)
labs <- 1:10
ggplot()+geom_text(aes(x=x,y=y,label=labs))

enter image description here

Tags:

Plot

R