简体   繁体   中英

Moving table created by annotation_custom with geom_bar plot

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))

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()

快速PNG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM