grid
-package包含一個用於生成軸的特殊工具。它將軸寫入當前視口之外,因此使用grobHeight
的高度因此被認爲是0mm。不幸的是我需要爲這個軸創造空間,我想知道這個物體的確切高度。下面是說明該問題的一個示例:獲取xaxisGrob的高度
library(grid)
plotColorBar <- function() {
grid.newpage()
xg <- xaxisGrob(at=c(0,.25,.5,.75, 1),
label= sprintf("%d %%", c(0,.25,.5,.75, 1)*100),
main=FALSE)
bar_layout <- grid.layout(nrow=3, ncol=3,
heights = unit.c(unit(.80, "npc"),
grobHeight(xg),
unit(.2, "npc") - grobHeight(xg)),
widths = unit.c(unit(.25, "npc"),
unit(1, "npc") -
unit(.5, "npc"),
unit(.25, "npc")))
pushViewport(viewport(layout=bar_layout, name="Bar_layout"))
pushViewport(viewport(layout.pos.row=3,
layout.pos.col=2,
name="Color_bar"))
grid.draw(xg)
bar_clrs <- colorRampPalette(c("red", "blue"), space="Lab")(101)
grid.raster(t(as.raster(bar_clrs)), width=1, height=1, interpolate=FALSE)
popViewport()
pushViewport(viewport(layout.pos.row=1,
layout.pos.col=1:3,
name="Main_exc_bar"))
grid.rect(gp=gpar(col="black", fill="#00000022"))
grid.text("Coool")
popViewport()
}
png(filename="axisWihtoutHeight.png", width=250, height=250, res=96)
plotColorBar()
dev.off()
提供了以下圖像:
注意,灰色區域覆蓋軸文本。當我嘗試convertY(grobHeight(xg), "mm")
時,它返回0mm。
現在應用@baptiste建議修復略微提高了圖像:
heightDetails.xaxis = function(x) do.call(sum, lapply(x$children, grobHeight))
png(filename="axisWihtHeight.png", width=250, height=250, res=96)
plotColorBar()
dev.off()
正如你可以看到由於某種原因,文本是高度的兩倍。通過下面的選項,雖然這個手動調節這也感到有點笨拙:
heightDetails.xaxis = function(x) {
grobHeight(x$children$ticks) +
grobHeight(x$children$labels) +
grobHeight(x$children$labels)
}
png(filename="axisWihtDoubleHeight.png", width=250, height=250, res=96)
plotColorBar()
dev.off()
最終解決
至於建議似乎單元(1.5 * CEX,「行」)做工作很好:
heightDetails.xaxis = function(x) {
cex <- 1
if (!is.null(x$children$labels$gp$cex))
cex <- x$children$labels$gp$cex
grobHeight(x$children$ticks) +
unit(1.5*cex, "line")
}
而不是加倍標籤高度,你應該顯然增加'unit(1.5,「line」)'......這個原因對我來說有些神祕,並隱藏在'grid ::: make.xaxis.labels '(從'drawDetails'到'makeContext'最近的一個變化,在這裏描述](https://www.stat.auckland.ac.nz/~paul/R/customGridRedesign.pdf)。說實話,我會設計我自己的軸grob,我從來沒有真正發現網格版非常吸引人。 – baptiste
,順便說一句,看看colorbar的rasterGrob,或者至少vectorise gpar()和rectGrob(不需要循環) – baptiste
@baptiste非常好,我添加了最終的代碼 - 它似乎工作很好,甚至可以調整cex參數,rasterGrob真棒。我不明白爲什麼在網格包中默認沒有包含高度函數,我已經猜到了高度到目前爲止的混合結果 - 這肯定會改善我的繪圖函數。 –