Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

plot - Adding table within the plotting region of a ggplot in r

I would like to add a table of the coordinates of highlighted site in a ggplot.

Using a previous question as example data:

set.seed(1)
mydata <- data.frame(a=1:50, b=rnorm(50))
ggplot(mydata,aes(x=a,y=b)) + 
    geom_point(colour="blue") + 
    geom_point(data=mydata[10:13, ], aes(x=a, y=b), colour="red", size=5)

enter image description here

I would like to add the following table to the lower right-hand corner of the plot within the plotting region. Any advice?

table<-cbind(sites=c("site 1","site 2","site 3","site 4"),mydata[10:13,])
table

    sites  a          b
    site 1 10 -0.3053884
    site 2 11  1.5117812
    site 3 12  0.3898432
    site 4 13 -0.6212406
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use ggplot2's annotation_custom with a tableGrob from the gridExtra package.

library(ggplot2)
library(gridExtra)
set.seed(1)
mydata <- data.frame(a=1:50, b=rnorm(50))
mytable <- cbind(sites=c("site 1","site 2","site 3","site 4"),mydata[10:13,])
k <- ggplot(mydata,aes(x=a,y=b)) + 
  geom_point(colour="blue") + 
  geom_point(data=mydata[10:13, ], aes(x=a, y=b), colour="red", size=5) + 
  annotation_custom(tableGrob(mytable), xmin=35, xmax=50, ymin=-2.5, ymax=-1)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...