I am plotting two lines using
plot(x, y, type = \"l\", color = \"red\")
and
points(x2, y2, type = \"l\", color = \"blue\")
locator()
is an interactive method of obtaining coordinates by clicking on an existing graph.
Here are instructions on how to use locator()
to find the right coordinates for a label on a graph.
Step 1: Plot a graph:
plot(1:100)
Step 2: Type the following into the console:
coords <- locator()
Step 3: Click once on the plot, then click Stop .. Stop Locator
at the top left of the plot (this returns control back to the R console).
Step 4: Find the returned coordinates:
coords
$x
[1] 30.26407
$y
[1] 81.66773
Step 5: Now, you can add a label to the existing plot using these coordinates:
text(x=30.26407, y=81.66773,label="This label appears where I clicked")
or
text(x=coords$x, y=coords$y,label="This label appears where I clicked")
Here is the result:
You'll notice that the label appears with its center where you clicked. Its better if the label appears with its first character where you clicked. To find the correct parameter, see the help for text
, and add the parameter pos=4
:
text(x=30,y=80,pos=4,label = "hello")
Notes:
legend()
to plot a label (this draws a box around the label which often looks nicer).ggplot2
instead of plot, as ggplot2
is the gold standard for producing graphs.You can use the locator()
within text()
by point&click method.
y <- rnorm(100, 10)
y2 <- rnorm(100, 20)
x <- 1:100
plot(x, y, type = "n", ylim = c(0, 40), xlim = c(0, 120))
lines(x, y)
lines(x, y2, col = "red")
text(locator(), labels = c("red line", "black line)"))
To use directlabels, you must structure your data in a data.frame and then use a high-level plotting system like ggplot2, or in the example below, lattice:
y <- rnorm(100, 10)
y2 <- rnorm(100, 20)
x <- 1:100
treatment <- rep(c("one group","another"),each=length(x))
df <- data.frame(x=c(x,x),y=c(y,y2),treatment)
library(lattice)
p <- xyplot(y~x,df,groups=treatment,type="l")
if(!require(directlabels)){
install.packages("directlabels")
library(directlabels)
}
print(direct.label(p))
print(direct.label(update(p,xlim=c(0,120)),last.points))
Instead of using locator(), you could also just make the label coordinates a function of your data. For example, piggy backing on Roman's demo:
text(x=rep(max(x)+3, 2), y=c(mean(y), mean(y2)), pos=4, labels=c('black line', 'red line'))