[英]Issues plotting a combined shapefile in R using ggplot, no defined error given
[英]Plotting a grid data on a map using a shapefile with ggplot in R
我想使用ggplot在世界地圖上繪制網格數據。
這是我在這篇文章之后嘗試的內容: R在地圖上繪制網格值 ,但出現錯誤。
數據:
require(maptools)
nasafile <- "http://eosweb.larc.nasa.gov/sse/global/text/global_radiation"
nasa <- read.table(file=nasafile, skip=13, header=TRUE)
然后,我加載了從此處下載的shapefile: 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
錯誤: 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
我想要的輸出將是在shapefile定義的地圖頂部繪制Annf
值,該文件僅是大陸的表面。
你有經度緯度和列nasa
,但不shapef
。 在ggplot中使用后者之前,必須先增強后者。
嘗試更換線
geom_path(data = shapef) +
與此相反:
geom_path(data = fortify(shapef), aes(x=long, y=lat, group=group)) +
編輯:
您的geom_tile()層覆蓋整個圖。 因此,如果僅希望將其顯示在陸地上,則需要覆蓋海洋。
問題1 :覆蓋海洋
土地的shapefile包含土地塊的多邊形,而不是海洋。 為了獲得可以遮蓋大海的多邊形,我從同一網站( http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_ocean.zip )獲得了多邊形:
shapef.sea <- readShapePoly(fn = "ne_110m_ocean.shp")
問題2 :shapefile中的孔
由於有被陸地完全包圍的陸地(例如,澳大利亞),所以海洋shapefile包含中間帶有“孔”的多邊形,並且ggplot不能很好地處理孔(在此處的文檔中討論)。
幸運的是, 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.