背景
在阅读了这个关于如何扩展 ggplot和我试图理解的相应小插图的ggplot
漂亮答案之后,如何扩展.
简而言之
我明白,这些部分是如何组合在一起的,但我错过了一个重要信息:如何ggplot
确定轴的默认范围?
代码
考虑以下玩具示例:
library(grid)
library(ggplot2)
GeomFit <- ggproto("GeomFit", GeomBar,
required_aes = c("x", "y"),
setup_data = .subset2(GeomBar, "setup_data"),
draw_panel = function(self, data, panel_scales, coord, width = NULL) {
bars <- ggproto_parent(GeomBar, self)$draw_panel(data,
panel_scales,
coord)
coords <- coord$transform(data, panel_scales)
tg <- textGrob("test", coords$x, coords$y * 2 - coords$ymin)
grobTree(bars, tg)
}
)
geom_fit <- function(mapping = NULL, data = NULL,
stat = "count", position = "stack",
...,
width = NULL,
binwidth = NULL,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomFit,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
width = width,
na.rm = na.rm,
...
)
)
}
set.seed(1234567)
data_gd <- data.frame(x = letters[1:5],
y = 1:5)
p <- ggplot(data = data_gd, aes(x = x, y = y, fill = x)) +
geom_fit(stat = "identity")
问题
如您所见,某些文本未显示。我假设以ggplot
某种方式计算轴的范围,因为它不知道我的textGrob
. 我该如何解决?(期望的结果相当于p + expand_limits(y = 10)
注意。当然,我可以通过要求添加手动比例将问题推给最终用户。但理想情况下,我希望正确设置秤。