添加在R A ggplot的绘图区域内表(Adding table within the plott

2019-06-18 01:30发布

我想补充的突出部位的坐标表的ggplot。

使用以前的问题作为示例数据:

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)

我想下面的表添加到绘图区域内的地块的右下角的角落。 有什么建议?

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

Answer 1:

您可以使用ggplot2annotation_customtableGrobgridExtra包。

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)



Answer 2:

@ user3206440,@Punintended一个简单的去除行号的方式存在:添加rows = NULL来调用tableGrob

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, rows=NULL), 
                    xmin=35, xmax=50, ymin=-2.5, ymax=-1)

请参阅gridExtra维基 。



Answer 3:

@ user3206440:我发现了一个变通办法,消除行号。 我格式化我的数据作为基体,指定列名,然后有tableGrob直接调用。 每当我有tableGrob把它作为一个数据帧,行名坚持。

下面是一个例子。 我敢肯定有应对chisq.test输出更简单的方法

chivalues <- chisq.test(chitable)
chidf <- matrix(c(unlist(c(round(as.numeric(chivalues[1]), 2),
                    chivalues[2], round(as.numeric(chivalues[3]), 5), numcells))),
                   nrow = 1, ncol = 4, byrow = FALSE)
colnames(chidf) <- c("Chi-Squared", "DF", "P Value", "Total Cells")

再后来......

annotation_custom(tableGrob(chidf), xmin=2, xmax=6, ymin=700, ymax=800)


Answer 4:

随着发布“GGPLOT2” 3.0.0和“ggpmisc” 0.3.0新的更简单的答案是可能的:

library(ggplot2)
library(ggpmisc)

set.seed(1)
mydata <- data.frame(a = 1:50, b = rnorm(50))
table <- cbind(sites=c("site 1", "site 2", "site 3", "site 4"), mydata[10:13, ])

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) +
  annotate(geom = "table", x = 37, y = -0.8, label = list(table), 
           vjust = 1, hjust = 0)

“GGPLOT2” 3.0.0完全支持tibbles(参见发布公告 ),它能够将数据帧的列表映射到label的审美。 新geom_table()在包“ggpmisc 0.3.0”利用了这一点,使得相加表格与语法类似的geom_label()可能(见文档 )。 这里似乎是最合适的表中添加作为注释,但当然geom_table()也可以直接使用,其他ggplot几何形状。



文章来源: Adding table within the plotting region of a ggplot in r
标签: r plot ggplot2