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)
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
With the release of 'ggplot2' 3.0.0 and 'ggpmisc' 0.3.0 a new simpler answer is possible:
'ggplot2' 3.0.0 fully supports tibbles (see release announcement) making it possible to map a list of data frames to the
label
aesthetic. The newgeom_table()
in package 'ggpmisc 0.3.0' takes advantage of this, making the addition of tables with a syntax similar to that ofgeom_label()
possible (see documentation). Here seemed most appropriate to add the table as an annotation, but of coursegeom_table()
can also be used directly, as otherggplot
geometries.You can use
ggplot2
'sannotation_custom
with atableGrob
from thegridExtra
package.@user3206440, @Punintended An easy way of removing row numbers exists: add
rows = NULL
to the call totableGrob
.Please see the gridExtra Wiki.
@user3206440: I found a work-around that removes row numbers. I formatted my data as a matrix, assigned column names, then had tableGrob call that directly. Whenever I had tableGrob call it as a data frame, the row name persisted.
Below is an example. I'm sure there's an easier way to deal with the chisq.test output
And then later...