简体   繁体   中英

R plot labels outside with lines from points

I need to produce automatically a plot where the dots are connected to their labels (which are outside) through a line. Is there a way to do this in R?. Thanks in advance.

See here an example: https://www.dropbox.com/s/4tepdp5j13ot2dd/Example.png?dl=0

set.seed(1)
x <- rnorm(10)
lab <- sample(1:10, 5)
par(mar = c(5,4,2,5))
plot(x)
p <- par('usr')
# l <- legend(p[2], p[4], legend = round(x[lab], 2), xpd = NA, bty = 'n')
l <- legend(p[2], p[4], legend = sprintf('Label%s', 1:5), xpd = NA, bty = 'n')
segments(lab, x[lab], l$text$x, l$text$y, xpd = NA, col = seq_along(lab))

在此处输入图片说明

Based on @rawr's solution:

set.seed(1)
x <- rnorm(10)
y <- rnorm(10)
z <- letters[1:10]
df<-data.frame(x,y,z)

lab <- df$z
plot(x,y)
p <- par('usr')
l <- legend(p[2], p[4], legend = lab, xpd = NA, bty = 'n')
segments(df$x, df$y, l$text$x, l$text$y, xpd = NA)

在此处输入图片说明

But now let's say that each label has more than 1 x,y pair:

set.seed(1)
x <- rnorm(20)
y <- rnorm(20)
z <- letters[10:1]
df<-data.frame(x,y,z)[order]

lab <- levels(df$z)
plot(x,y)
p <- par('usr')
l <- legend(p[2], p[4], legend =lab, xpd = NA, bty = 'n')
lab_df<-data.frame(x=l$text$x, y=l$text$y, z=lab)
do_seg<-function(i){
  segments(df[df$z==i,]$x, df[df$z==i,]$y, lab_df[lab_df$z==i,]$x, lab_df[lab_df$z==i,]$y, xpd = NA)
}
lapply(lab,do_seg)

Gives us:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM