The text
function arguments have a specific order (type ?text
into the console), and when you don't use argument names the function fills the arguments in the order you've given. It seems you forgot to define y=
or so.
Try this:
plot(mtcars$wt, type='h', ylim=c(0,6))
abline(h=4)
## here your old call with argument names
# text(x=mtcars$wt, y=row.names(mtcars[mtcars$wt >4,]), pos =3, col='blue', cex=0.6)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4],
labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6)

However, the labels are a bit lumped together. Here we could use Map
that applies each argument one by one to the text
function, and where we are able to add an adjustment vector to x
and y
arguments.
plot(mtcars$wt,type='h',ylim=c(0,6))
abline(h=4)
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
x=which(mtcars$wt > 4) + c(0, -2.8, 0, 2.2),
y=mtcars$wt[mtcars$wt > 4] + c(0, -.1, .1, -.1),
labels=row.names(mtcars[mtcars$wt > 4,])
)

When we have more labels this might still look confusing to readers. Then we could use arrows
which positions are defined in startpoints x0, y0
and endpoints x1, y1
and where we use the values we already have.
plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
xpos. <- which(mtcars$wt > 4)
ypos. <- mtcars$wt[mtcars$wt > 4]
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
x=xpos. + c(0, -6, 0, 6), y=ypos. + c(0, 1, 2, 1),
labels=row.names(mtcars[mtcars$wt > 4,])
)
arrows(x0=xpos. + c(0, -6, 0, 6), y0=ypos.+ c(0, 1, 2, 1), x1=xpos., y1=ypos.+.2,
code=0, col="blue")

To rotate the labels, we can use srt=
option, e.g. srt=45
for 45°.
plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4],
labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6, srt=45)
Note: Better use another device than the preview window, such as png()
or pdf()
, because otherwise everything shifts annoyingly all the time. See answers to this question on how to do this:
Now, have fun with tinkering! :)