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

R语言中无法叠加两层地图的问题求助

Hey there! Let's break down this error and fix your code step by step.

Why the Error Happens

That plot.new has not been called yet error boils down to a misused parameter in your first plot call:

  • The reset = FALSE argument in sf's plot function tells R not to create a new plotting window (it skips running plot.new() under the hood).
  • Since this is the first plot in your script, there's no existing plotting window to work with. When you try to add the red Asia layer with add = TRUE, R can't find an open canvas to draw on—hence the error.

How to Fix It

The simplest fix is to remove reset = FALSE from your first plot. By default, sf's plot function creates a new plotting window when you first use it, which lets you add layers later with add = TRUE:

library(spData)
world_asia = world[world$continent == "Asia", ]
asia = st_union(world_asia)
# First plot creates the window (no need for reset=FALSE)
plot(world["pop"])
# Add the red Asia layer to the existing plot
plot(asia, add = TRUE, col = "red")

If you do need reset = FALSE for a more complex multi-layer workflow, you'll need to manually create a plotting window first and set the correct coordinate limits:

library(spData)
world_asia = world[world$continent == "Asia", ]
asia = st_union(world_asia)

# Manually create a new plotting window
plot.new()
# Set limits to match the world map's bounding box
plot.window(xlim = st_bbox(world)[c(1,3)], ylim = st_bbox(world)[c(2,4)])
# Plot population data without resetting the window
plot(world["pop"], reset = FALSE, add = TRUE)
# Add the red Asia layer
plot(asia, add = TRUE, col = "red")
# Optional: Add axes and a border to clean up the plot
axis(1); axis(2); box()

Quick Tip

When working with sf objects, using st_geometry() to plot just the spatial shapes can make layer stacking more predictable:

plot(world["pop"])
plot(st_geometry(asia), add = TRUE, col = "red")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:22:36