Moving table created by annotation_custom with geom_bar plot

♀尐吖头ヾ 提交于 2019-12-11 03:21:59

问题


I tried searching for answers but couldn't find anything.

I have have a plot and want to add a table within the plot itself. I can do it but the table ends up being right in the middle.

It is possible to relocate a table created by annotation_custom if the x-axis is discrete? If so, how?

Thank you!

For example, I want to relocate this table.

library(ggplot2)
library(gridExtra)

my.summary <- summary(chickwts$weight)
my.table   <- data.frame(ids = names(my.summary), nums = as.numeric(my.summary))
ggplot(chickwts, aes(feed, weight)) +
       geom_bar(stat = "identity")  +
       annotation_custom(tableGrob(my.table))

回答1:


The custom annotation in ggplot2 can be rearragned inside the plotting area. This at least moves them out of the center. Maybe this solution is already sufficient for you. I'll try and tweak this. It should be possible to put this outside the plotting area as well.

library(ggplot2)
library(gridExtra)

my.summary <- summary(chickwts$weight)
my.table   <- data.frame(ids = names(my.summary), nums = as.numeric(my.summary))
ggplot(chickwts, aes(feed, weight)) +
       geom_bar(stat = "identity")  +
       annotation_custom(tableGrob(my.table), xmin=5,xmax=6,ymin=300,ymax=1300)

EDIT:

To place the table outside the plot, regardless of what the plot consists of, the grid package could be used:

library(ggplot2)
library(gridExtra)
library(grid)

# data
my.summary <- summary(chickwts$weight)
my.table   <- data.frame(ids = names(my.summary), nums = as.numeric(my.summary))

# plot items
my.tGrob <- tableGrob(my.table)
plt <- ggplot(chickwts, aes(feed, weight)) +
          geom_bar(stat = "identity")

# layout
vp.layout <- grid.layout(nrow=1, ncol=2, heights=unit(1, "null"),
  widths=unit(c(1,9), c("null","line")) )

# start drawing
grid.newpage()
pushViewport(viewport(layout=vp.layout, name="layout"))
# plot
pushViewport(viewport(layout.pos.row=1, layout.pos.col=1, name="plot"))
print(plt, newpage=FALSE)
upViewport()
# table
pushViewport(viewport(layout.pos.row=1, layout.pos.col=2, name="table"))
grid.draw(my.tGrob)
upViewport()

#dev.off()



来源:https://stackoverflow.com/questions/25353206/moving-table-created-by-annotation-custom-with-geom-bar-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!