2012-11-04 24 views
20

Ben tartışma için buraya örnek kullanıyorum ülkelerin haritası yarıları: Bir değişkeni eşlemek istiyorum enter image description heredünya haritası - Farklı renkler

: ggplot map with l

library(rgdal) 
library(ggplot2) 
library(maptools) 

# Data from http://thematicmapping.org/downloads/world_borders.php. 
# Direct link: http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip 
# Unpack and put the files in a dir 'data' 

gpclibPermit() 
world.map <- readOGR(dsn="data", layer="TM_WORLD_BORDERS_SIMPL-0.3") 
world.ggmap <- fortify(world.map, region = "NAME") 

n <- length(unique(world.ggmap$id)) 
df <- data.frame(id = unique(world.ggmap$id), 
       growth = 4*runif(n), 
       category = factor(sample(1:5, n, replace=T))) 

## noise 
df[c(sample(1:100,40)),c("growth", "category")] <- NA 


ggplot(df, aes(map_id = id)) + 
    geom_map(aes(fill = growth, color = category), map =world.ggmap) + 
    expand_limits(x = world.ggmap$long, y = world.ggmap$lat) + 
    scale_fill_gradient(low = "red", high = "blue", guide = "colorbar") 

aşağıdaki sonuçları verir Bir ülkenin sol "yarısı" ve ülkenin sağ "yarısı" için farklı bir değişken. Alıntıya "yarım" koydum çünkü açıkça tanımlanmadı (ya da en azından açıkça tanımlamamıştım). Ian Fellows'ın yanıtı yardımcı olabilir (bu da centroid'i elde etmenin kolay bir yoludur). Bir şey için umuyoruz, böylece örnekte aes(left_half_color = growth, right_half_color = category) yapabilirim. Farklıysa, üst yarım ve alt yarısı da ilgileniyorum. Mümkünse, yarımların tek tek merkezlerini de bir şeyle eşleştirmek istiyorum.

+7

Sen iki harita yan yana olan düşünebilir. Ülkenin bu bölünmesinden daha iyi anlaşılması ve yorumlanması çok daha mantıklı olabilir. –

+0

@Marcinthebox öneri için teşekkürler. –

cevap

26

Bu, ggplot olmadan, plot işlevine dayanan bir çözümdür. Ayrıca OP koduna ek olarak rgeos paketini gerektirir:% 10 daha az görsel ağrı ile Şimdi

DÜZENLEME

DÜZENLEME 2 doğuda için centroids ile Şimdi ve batı yarıları

library(rgeos) 
library(RColorBrewer) 

# Get centroids of countries 
theCents <- coordinates(world.map) 

# extract the polygons objects 
pl <- slot(world.map, "polygons") 

# Create square polygons that cover the east (left) half of each country's bbox 
lpolys <- lapply(seq_along(pl), function(x) { 
    lbox <- bbox(pl[[x]]) 
    lbox[1, 2] <- theCents[x, 1] 
    Polygon(expand.grid(lbox[1,], lbox[2,])[c(1,3,4,2,1),]) 
}) 

# Slightly different data handling 
wmRN <- row.names(world.map) 

n <- nrow([email protected]) 
[email protected][, c("growth", "category")] <- list(growth = 4*runif(n), 
       category = factor(sample(1:5, n, replace=TRUE))) 

# Determine the intersection of each country with the respective "left polygon" 
lPolys <- lapply(seq_along(lpolys), function(x) { 
    curLPol <- SpatialPolygons(list(Polygons(lpolys[x], wmRN[x])), 
    proj4string=CRS(proj4string(world.map))) 
    curPl <- SpatialPolygons(pl[x], proj4string=CRS(proj4string(world.map))) 
    theInt <- gIntersection(curLPol, curPl, id = wmRN[x]) 
    theInt 
}) 

# Create a SpatialPolygonDataFrame of the intersections 
lSPDF <- SpatialPolygonsDataFrame(SpatialPolygons(unlist(lapply(lPolys, 
    slot, "polygons")), proj4string = CRS(proj4string(world.map))), 
    [email protected]) 

########## 
## EDIT ## 
########## 
# Create a slightly less harsh color set 
s_growth <- scale([email protected]$growth, 
    center = min([email protected]$growth), scale = max([email protected]$growth)) 
growthRGB <- colorRamp(c("red", "blue"))(s_growth) 
growthCols <- apply(growthRGB, 1, function(x) rgb(x[1], x[2], x[3], 
    maxColorValue = 255)) 
catCols <- brewer.pal(nlevels([email protected]$category), "Pastel2") 

# and plot 
plot(world.map, col = growthCols, bg = "grey90") 

plot(lSPDF, col = catCols[[email protected]$category], add = TRUE) 

enter image description here

Belki biri w gelebilir ggplot2 kullanarak iyi bir çözüm. Ancak, tek bir grafik için ("Yapamazsınız") çoklu doldurma ölçekleriyle ilgili bir soruyu this answer'a dayanarak, ggplot2 çözümünün, hiçbir şey yapmadan görünmesi olası değildir (bu, yukarıdaki yorumlarda önerildiği gibi iyi bir yaklaşım olabilir).


DÜZENLEME re: bir şeye yarıdan haritalama sentroidler: batı ("doğru" için

coordinates(lSPDF) 

olanlar tarafından yarıları elde edilebilir ("sol") doğu için centroids) yarıları benzer bir şekilde bir rSPDF nesne oluşturarak elde edilebilir:

# Create square polygons that cover west (right) half of each country's bbox 
rpolys <- lapply(seq_along(pl), function(x) { 
    rbox <- bbox(pl[[x]]) 
    rbox[1, 1] <- theCents[x, 1] 
    Polygon(expand.grid(rbox[1,], rbox[2,])[c(1,3,4,2,1),]) 
}) 

# Determine the intersection of each country with the respective "right polygon" 
rPolys <- lapply(seq_along(rpolys), function(x) { 
    curRPol <- SpatialPolygons(list(Polygons(rpolys[x], wmRN[x])), 
    proj4string=CRS(proj4string(world.map))) 
    curPl <- SpatialPolygons(pl[x], proj4string=CRS(proj4string(world.map))) 
    theInt <- gIntersection(curRPol, curPl, id = wmRN[x]) 
    theInt 
}) 

# Create a SpatialPolygonDataFrame of the western (right) intersections 
rSPDF <- SpatialPolygonsDataFrame(SpatialPolygons(unlist(lapply(rPolys, 
    slot, "polygons")), proj4string = CRS(proj4string(world.map))), 
    [email protected]) 
Daha sonra bu bilgi uygun harita üzerinde çizilen olabilir

lSPDF veya rSPDF centroids:

points(coordinates(rSPDF), col = factor([email protected]$REGION)) 
# or 
text(coordinates(lSPDF), labels = [email protected]$FIPS, cex = .7) 
+0

Mükemmel cevabınız (ve güncellemeler için) için teşekkür ederiz. Aşağıdaki web sitesindeki tavsiyelere uyursam, yaptığınız şeyi ggplot2 için birleştirmeme izin verecek mi? https://github.com/hadley/ggplot2/wiki/plotting-polygon-shapefiles –

+0

@XuWang, Bağlantılı yönergeleri kullanarak 'lSPDF' ve' rSPDF 'biçim dosyalarını çizebilmeniz gerekir, ancak AFAIK sorunlara dönüşecek Her bir yarısı için farklı "dolgu" eşlemelerini istiyorsanız. Yardım ve yanıtlarınız/güncellemeleriniz için – BenBarnes

+0

teşekkürler. –

İlgili konular