gpt4 book ai didi

r - 角落缺少geom_tile边框

转载 作者:行者123 更新时间:2023-12-04 01:51:45 25 4
gpt4 key购买 nike

我有以下数据框:

# Dummy data frame
df <- expand.grid(x = 1:3, y = 1:3)
我想像这样使用 geom_tile将其绘制为 ggplot2:
# Tile plot
ggplot(df) +
geom_tile(aes(x = x, y = y),
fill = NA, colour = "red", size = 3, width = 0.7, height = 0.7)
这使,
enter image description here
但是请注意,在每个图块的左上角都缺少一个缺口,在该缺口处边框不能完全正确地相吻合。如果使用 geom_rect,我将得到相同的结果。是否有解决方法来避免这种情况?
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] ggplot2_3.1.0 kitchendraw_0.1.0

loaded via a namespace (and not attached):
[1] Rcpp_1.0.0 rstudioapi_0.8 bindr_0.1.1 magrittr_1.5 tidyselect_0.2.5 munsell_0.5.0 colorspace_1.3-2
[8] R6_2.3.0 rlang_0.3.0.1 plyr_1.8.4 dplyr_0.7.7 tools_3.5.1 grid_3.5.1 gtable_0.2.0
[15] withr_2.1.2 yaml_2.2.0 lazyeval_0.2.1 assertthat_0.2.0 tibble_1.4.2 crayon_1.3.4 bindrcpp_0.2.2
[22] purrr_0.2.5 glue_1.3.0 labeling_0.3 compiler_3.5.1 pillar_1.3.0 scales_1.0.0 pkgconfig_2.0.2

更新了图以回应以下评论
enter image description here

最佳答案

如其他人所述,这是由于lineend规范所致,可以在environment(GeomTile$draw_panel)$f中找到该规范:

function (self, data, panel_params, coord) 
{
if (!coord$is_linear()) {
... #omitted for space
}
else {
coords <- coord$transform(data, panel_params)
ggname("geom_rect",
rectGrob(coords$xmin, coords$ymax,
width = coords$xmax - coords$xmin, height = coords$ymax -
coords$ymin, default.units = "native", just = c("left", "top"),
gp = gpar(col = coords$colour,
fill = alpha(coords$fill, coords$alpha),
lwd = coords$size * .pt,
lty = coords$linetype,
lineend = "butt"))) # look here
}
}
geom_tile层的创建由 rectGrob支持,其硬编码 lineend参数值为“butt”。下图(找到 here)很好地说明了3个 lineend值之间的差异:

lineend values

如果您想深入研究底层 GeomTile的功能并更改代码中所有 geom_tile层的图形参数,则可以执行此操作。 (我最近用该解决方案回答了类似的 question。)但是,对于单个绘图,我只是将ggplot转换为grob对象,并使用那里的 gp参数来代替:
library(grid)
gp <- ggplotGrob(p)
grid.draw(gp)

# this "sharpens" the top left corner
gp$grobs[[which(grepl("panel", gp$layout$name))]]$children[[3]]$gp$lineend <- "square"
grid.draw(gp)

plot after changing line end
# this further "sharpens" the other three corners
gp$grobs[[which(grepl("panel", gp$layout$name))]]$children[[3]]$gp$linejoin <- "mitre"
grid.draw(gp)

plot after changing line join

注意:与 geom_tile对应的正确grob的实际位置不一定是 gp$grobs[[which(grepl("panel", gp$layout$name))]]$children[[3]]$gp$linejoin。这里是 children[[3]],但是ggplot对象中的其他geom层(在 geom_tile层之下或之上)可以移动其相对位置。在这种情况下,您可能需要检查控制台中 gp$grobs[[which(grepl("panel", gp$layout$name))]]$children的输出,以标识正确的位置编号。

关于r - 角落缺少geom_tile边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53767758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com