2017-08-10 65 views
0

使用Shape文件與ggplot我想繪製使用ggplot的世界地圖的頂格數據地圖上的網格數據。繪圖中的R

這就是我試過的這個帖子:R plot grid value on maps,但我得到了一個錯誤。

數據:

require(maptools) 
nasafile <- "http://eosweb.larc.nasa.gov/sse/global/text/global_radiation" 
nasa <- read.table(file=nasafile, skip=13, header=TRUE) 

然後,我裝從這裏下載shape文件:http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_land.zip

shapef <- readShapeLines(fn = "shapefiles/ne_110m_land.shp") 

因爲我想以後使用geom_scatterpie功能我轉換Ann值,我想繪製成因素並製作調色板。

nasa$Annf <- as.factor(as.character(nasa$Ann)) 
mypalette <- colorRampPalette(brewer.pal(9,"YlOrRd"))(533) 

然後我用ggplot繪製的數據:

ggplot(aes(y = Lat , x = Lon), data = nasa)+ 
    geom_tile(aes(fill=Annf)) + 
    guides(fill=FALSE) + 
    geom_path(data = shapef) + 
    scale_fill_manual(values = mypalette) + 
    theme_void() + 
    coord_equal() 

但我得到這個錯誤: Error in eval(expr, envir, enclos) : object 'Lon' not found

即使Lon列存在於我的數據幀:

head(nasa) 
    Lat Lon Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Ann Annf 
1 -90 -180 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19 
2 -90 -179 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19 
3 -90 -178 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19 
4 -90 -177 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19 
5 -90 -176 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19 
6 -90 -175 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19 

我希望的輸出,將有第th e Annf值繪製在由shapefile定義的地圖頂部,該地圖只是陸地表面。

回答

1

您有經度&緯度列nasa,但不是shapef。後者需要在ggplot中使用之前加強。

嘗試用這個,而不是替換線

geom_path(data = shapef) + 

geom_path(data = fortify(shapef), aes(x=long, y=lat, group=group)) + 

編輯:

你geom_tile()層覆蓋整個小區。所以如果你只想讓它在大陸上展示,你就需要覆蓋海洋。

問題1:覆蓋海洋

土地shape文件包含了陸地,沒有海洋的多邊形。爲了獲得該會掩蓋海多邊形,我得到了來自同一個站點(http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_ocean.zip)對應:

shapef.sea <- readShapePoly(fn = "ne_110m_ocean.shp") 

問題2:孔在shape文件

因爲有陸地完全海上(如澳大利亞)包圍,海洋shape文件包含在中間「洞」的多邊形,& ggplot不處理孔很好(其文檔here中討論)。

幸運的是,ggpolypath包正是爲此目的而創建的。

require(ggpolypath) 
ggplot(aes(y = Lat , x = Lon), data = nasa) + 
    geom_tile(aes(fill=Annf)) + 
    guides(fill=FALSE) + 
    geom_polypath(data = fortify(shapef.sea), aes(x=long, y=lat, group=group), fill = "steelblue2") + 
    geom_path(data = fortify(shapef), aes(x=long, y=lat, group=group)) + 
    scale_fill_manual(values = mypalette) + 
    theme_void() + 
    coord_equal() 

enter image description here

+0

感謝。我沒有得到錯誤,現在所有的國家都根據shapefile進行了概述。但我仍然希望將太陽輻射值僅繪製在國家上,即海洋不應該有任何顏色。 – GabrielMontenegro