Вертикальное выравнивание gridExtra tableGrob (R grid graphics/grob)
Возникли проблемы с выравниванием графического объекта сетки - прочитал все документы, которые я могу найти, включая книгу Мюррелла, но безуспешно. Я думаю, что я пытаюсь сделать это довольно просто, так что, надеюсь, я скучаю по простому.
Вот воспроизводимый пример, который сделает PDF всех авиаперевозчиков по месту назначения в Хэдли hflights
пакет (отражает то, что я пытаюсь сделать на другом наборе данных).
require(hflights)
require(gridExtra)
require(Cairo)
make_table <- function(df) {
p <- tableGrob(
df
,padding.h=unit(.25, "mm")
,show.rownames=FALSE
,gpar.coretext = gpar(fontsize=8, lineheight=0)
#this doesn't seem to justify the table
,just = c("bottom")
,show.box = T
)
return(p)
}
dests <- unique(hflights$Dest)
#list to hold the plots
plot_list <- list()
#loop over destinations and make a simple report
for (i in dests) {
#just this destination
this_dest <- hflights[hflights$Dest == i, ]
#the title
title <- textGrob(label = i, gp = gpar(fontsize=72, fontface = 'bold'))
#a table of carriers
carriers <- unique(this_dest$UniqueCarrier)
carriers <- data.frame(
carrier=carriers
)
carrier_table <- make_table(carriers)
#put them together
p <- arrangeGrob(
title, carrier_table
,nrow=2
)
plot_list[[i]] <- p
}
#print the report
Cairo(
width = 11, height = 8.5
,file = paste('destinations.pdf', sep = ''), type="pdf"
,units = "in"
)
print(plot_list)
dev.off()
Я хочу, чтобы вся таблица производилась tableGrob
(в make_table
функция), чтобы оправдать к вершине гроба. Прямо сейчас он центрирован вертикально и горизонтально внутри гроба. Нужно ли делать это в звонке tableGrob
или это в arrangeGrob
вызов? Иными словами, если вышеизложенное неясно, как я могу сделать выравнивание всей таблицы (а не текста внутри нее) по верху / низу / слева / справа от ее контейнера?
Спасибо!
1 ответ
Попробуй это,
library(gridExtra)
justify <- function(x, hjust="center", vjust="center", draw=TRUE){
w <- sum(x$widths)
h <- sum(x$heights)
xj <- switch(hjust,
center = 0.5,
left = 0.5*w,
right=unit(1,"npc") - 0.5*w)
yj <- switch(vjust,
center = 0.5,
bottom = 0.5*h,
top=unit(1,"npc") - 0.5*h)
x$vp <- viewport(x=xj, y=yj)
if(draw) grid.draw(x)
return(x)
}
g <- tableGrob(iris[1:3,1:2])
grid.newpage()
justify(g,"right", "top")