1

Is there an easier way to add a data.frame as a "textbox" to a plot? I did it "manually", using function legend.

plot(density(rnorm(1000)), xlab='x', ylab='y', lwd=1, main='Call', col='blue', type='l')
lines(density(rnorm(1000, 0, 2)), lty=3, col='red')
eo1 <- c(rnorm(1), rnorm(1), rnorm(1))
eo1 <- cbind(eo1, c(rnorm(1), rnorm(1), rnorm(1)))
colnames(eo1) <- c('contextA', 'contextB')
legend('topleft', legend=c(paste('medida', paste(colnames(eo1)[1:2], collapse='  '))
                           , paste('mean       ', paste(sprintf('%+.3f', eo1[2, 1:2]), collapse='     '))
                           , paste('sk            ', paste(sprintf('%+.3f', eo1[2, 1:2]), collapse='     '))
                           , paste('krtE         ', paste(sprintf('%+.3f', eo1[3, 1:2]), collapse='     '))
), horiz=F, cex=.7)

I could not see how Extent of boundary of text in R plot could help.
plot(density(rnorm(1000)),xlab='x',ylab='y',lwd=1,main='Call',col='blue',type='l');
lines(density(rnorm(1000,0,2)),lty=3,col='red')
eo1=cbind(rnorm(1),rnorm(1)); eo1=rbind(eo1,cbind(rnorm(1),rnorm(1)))
eo1=rbind(eo1,cbind(rnorm(1),rnorm(1)))
colnames(eo1)=c('contextA','contextB')
legend('topleft',legend=c(paste('medida',paste(colnames(eo1)[1:2],collapse='  '))
,paste('mean       ',paste(sprintf('%+.3f',eo1[2,1:2]),collapse='     '))
,paste('sk            ',paste(sprintf('%+.3f',eo1[2,1:2]),collapse='     '))
,paste('krtE         ',paste(sprintf('%+.3f',eo1[3,1:2]),collapse='     '))
),horiz=F,cex=.7)

jay.sf
  • 60,139
  • 8
  • 53
  • 110
xm1
  • 1,663
  • 1
  • 17
  • 28

2 Answers2

1

What about {plotrix}:

library(plotrix)

plot(1:10)
addtable2plot(head(iris), x = 1, y = 10, yjust = 0)

plotrix example

I_O
  • 4,983
  • 2
  • 2
  • 15
1

You may elaborate on sprntf, for instance by using \tabstops instead of spaces, and use text in a Map instead of legend.

set.seed(42)

plot(density(rnorm(1000)), xlab='x', ylab='y', lwd=1, main='Call', col='blue', type='l')
lines(density(rnorm(1000, 0, 2)), lty=3, col='red')
eo1 <- c(rnorm(1), rnorm(1), rnorm(1))
eo1 <- cbind(eo1, c(rnorm(1), rnorm(1), rnorm(1)))
colnames(eo1) <- c('contextA', 'contextB')

leg <- c(sprintf('medida\t%s\t%s', colnames(eo1)[1], colnames(eo1)[2]),
         sprintf('mean\t%+.3f\t%+.3f', eo1[1, 1], eo1[2, 2]),
         sprintf('sk\t\t%+.3f\t%+.3f', eo1[2, 1], eo1[2, 2]),
         sprintf('krtE\t\t%+.3f\t%+.3f', eo1[3, 1], eo1[2, 2]))

Map(\(x, y, z) text(par()$usr[1] + .125, y, leg[x], adj=0, font=z, cex=.8), 
    seq_along(leg), rev(seq_along(leg) * .025) + .3, c(3, 1, 1, 1))

enter image description here

You can also try eo1 <- format(round(eo1, 3)) and replace %+.3f by %s, which aligns the values (more or less) while avoiding the + sign.

jay.sf
  • 60,139
  • 8
  • 53
  • 110