簡體   English   中英

使用ggplot2在R中合並多個地圖

[英]Combine multiple maps in R using ggplot2

這是我所面臨問題的可復制示例。 我試圖在多個階段使用ggplot2創建地圖。 這是我面臨的問題。 考慮在墨西哥邊界border.county具有美國州多邊形的數據border ,在這些州具有邊界州的border.county 以下代碼可讓您獲取數據:

library(maps)
library(ggmap)
library(ggplot2)

USA <- get_googlemap(center = 'usa', zoom = 4,  
                     style = 'administrative|element:labels|visibility:off')

us.df <- map_data("state") 
border <- subset(us.df, 
                 region %in% c("california","arizona","new mexico","texas"))

counties <- map_data("county")
border.county <- subset(counties,
                        region %in% c("california","arizona","new mexico","texas"))

現在,我要創建一個地圖,並以Google Maps的地圖為背景,並使用州多邊形和縣邊界。 如果我執行以下操作,它將可以正常工作:

Allmap <- ggmap(USA) + 
  geom_polygon(aes(x = long, y = lat, fill = region, group = group), 
               data=border,  color = "white") +
  geom_polygon(aes(x = long, y = lat,  group = group), 
               data=border.county, fill=NA, color="red") 

現在,如果我想分多個階段創建此地圖,則會遇到問題。 我只需要縣邊界作為背景信息(作為一種“經常性主題”),並且我將在州一級創建具有變化信息的多個地圖。 因此,我與縣一起創建了“背景地圖”,效果很好:

Countmap <- ggmap(USA) + 
  geom_polygon(aes(x = long, y = lat,  group = group), 
               data=border.county, fill=NA, color="red") 

現在,我嘗試將其與狀態圖結合起來:

Statmap <- ggmap(USA) + 
  geom_polygon(aes(x = long, y = lat, fill = region, group = group), 
               data=border,  color = "white") + 
  Countmap

這給了我錯誤:

 Error: Don't know how to add o to a plot

我該如何解決? 我可以用其他方式組合地圖(例如: Statmap <- Countmap + geom_polygon(aes(x = long, y = lat, fill = region, group = group), data=border, color = "white") )) ; 但是,這使各縣處於州界之下。

我也知道這個特定的問題很容易解決,只需先繪制一張州的地圖,然后再將其與各縣合並。 但是,在我的實際情況中,這不是一個選擇,因為地圖的重復主題需要繪制在第二位:城市和地理邊界(例如此處的縣邊界)。

這是我要創建的地圖:

在此處輸入圖片說明

如果我正確理解了您的描述,則您不想合並地圖 您想要組合圖層 ,特別是在變化的州級地圖上覆蓋縣輪廓。

嘗試這個:

# define county outlines as a geom_polygon layer
county.layer <- geom_polygon(aes(x = long, y = lat, group = group),
                             data = border.county, fill = NA, color = "red")

# add county.layer as the last layer to your state-level map
Statmap <- ggmap(USA) + 
  geom_polygon(aes(x = long, y = lat, fill = region, group = group), 
               data=border,  color = "white") +
  county.layer

Statmap

單層圖

編輯以回應評論

如果要繪制多個縣圖層,請將它們放在列表中:

border.county2 <- subset(counties, region %in% c("montana")) 

layer2 <- list(geom_polygon(aes(x = long, y = lat, group = group), 
                            data = border.county2, fill = NA, color = "blue"),
               geom_polygon(aes(x = long, y = lat, group = group), 
                            data = border.county, fill = NA, color = "red"))

Statmap <- ggmap(USA) + 
  geom_polygon(aes(x = long, y = lat, fill = region, group = group), 
               data=border,  color = "white") +
  layer2

多層圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM