You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何消除Quarto Reveal.js中R的geom_sf绘图白色边框?

解决Quarto RevealJS深色主题下geom_sf绘图的白色边框问题

问题描述

在Quarto的RevealJS深色主题文档中,使用geom_sf绘制的ggplot地图会出现多余的白色边框。虽然反复调整#| fig-width和#| fig-height参数能消除空白,但过程繁琐,需要更高效的解决方式。

示例文档配置:

---
title: "test"
footer: "test "
author: "me"
format: revealjs
theme: dark
editor: visual
---

问题复现代码:

library(ggplot2)
library(maps)
library(ggdark)
world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))
ggplot() + geom_sf(data = world1) + dark_theme_gray() 

对比无白色边框的普通ggplot示例:

ggplot(mtcars, aes(x = wt, y = mpg)) +
 geom_point() + dark_theme_gray()

简便解决方法

方法1:固定坐标范围+消除绘图边距

通过coord_sf()严格使用地理数据的边界范围,同时用theme()把绘图边距设为0,彻底避免自动扩展导致的空白:

library(ggplot2)
library(maps)
library(ggdark)
library(sf)

world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))
bbox <- st_bbox(world1)

ggplot() +
  geom_sf(data = world1) +
  dark_theme_gray() +
  theme(plot.margin = margin(0, 0, 0, 0, "pt")) +  # 移除绘图区边距
  coord_sf(
    xlim = bbox[c(1, 3)],
    ylim = bbox[c(2, 4)],
    expand = FALSE  # 禁止自动扩展坐标范围
  )

方法2:设置块选项的宽高比

根据地理数据的边界计算合适的宽高比,通过Quarto块选项fig.asp直接应用,无需手动试错:

library(ggplot2)
library(maps)
library(ggdark)
library(sf)

world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))
# 计算宽高比:(y轴范围)/(x轴范围)
# asp <- (st_bbox(world1)$ymax - st_bbox(world1)$ymin)/(st_bbox(world1)$xmax - st_bbox(world1)$xmin)

ggplot() + geom_sf(data = world1) + dark_theme_gray() 

注:上述fig.asp=0.53是世界地图的近似宽高比,也可直接用代码计算的asp值动态设置。

方法3:用patchwork强制统一绘图尺寸

如果需要多图对齐,可借助patchwork包强制锁定绘图区域大小:

library(ggplot2)
library(maps)
library(ggdark)
library(patchwork)

world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))

p <- ggplot() + geom_sf(data = world1) + dark_theme_gray()
p + plot_layout(widths = 1, heights = 1) & theme(plot.margin = margin(0,0,0,0))

内容的提问来源于stack exchange,提问作者Cedric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 15:18:19