Ham*_*mao 14 r ggplot2 density-plot
我试图描绘我正在阿拉伯/波斯湾研究的某些生物的生态分布.以下是我尝试过的代码示例:
背景层
library(ggplot2)
library(ggmap)
nc <- get_map("Persian Gulf", zoom = 6, maptype = 'terrain', language = "English")
ncmap <- ggmap(nc, extent = "device")
Run Code Online (Sandbox Code Playgroud)
其他层
ncmap+
stat_density2d(data=sample.data3, aes(x=long, y=lat, fill=..level.., alpha=..level..),geom="polygon")+
geom_point(data=sample.data3, aes(x=long, y=lat))+
geom_point(aes(x =50.626444, y = 26.044472), color="red", size = 4)+
scale_fill_gradient(low = "green", high = "red") + scale_alpha(range = c(0.00, 0.25), guide = FALSE)
Run Code Online (Sandbox Code Playgroud)
但是,我想用它stat_density2d来显示数百种物种的分布(在列中记录,例如SP1 ...... SPn),而不仅仅是显示纬度和经度.
我对你的问题的处理方法是一种务实的方法:只需将海湾国家层放在热图分布上即可。这会相应地裁剪热图。但请注意,热图仍按未裁剪的方式进行计算。这意味着密度计算不仅限于水体,而是简单地在视觉上进行裁剪。
为了重现性,以下代码假设您已解压.rar@Hammao 提供的文件并在结果文件夹中执行代码Persian Gulf。
# get sample data
sample.data <- read.csv("sample.data3.csv")
Run Code Online (Sandbox Code Playgroud)
现在,我们需要获取海湾国家的国家形状。我rworldmap为此使用该包。
# loading country shapes
library(rworldmap)
# download map of the world
worldmap <- getMap(resolution = "high") # note that for 'resolution="high"'
# you also need the "rworldxtra" pkg
# extract Persian Gulf countries...
gulf_simpl <- worldmap[worldmap$SOVEREIGNT == "Oman" |
worldmap$SOVEREIGNT == "Qatar" |
worldmap$SOVEREIGNT == "United Arab Emirates" |
worldmap$SOVEREIGNT == "Bahrain" |
worldmap$SOVEREIGNT == "Saudi Arabia" |
worldmap$SOVEREIGNT == "Kuwait" |
worldmap$SOVEREIGNT == "Iraq" |
worldmap$SOVEREIGNT == "Iran", ]
# ... and fortify the data for plotting in ggplot2
gulf_simpl_fort <- fortify(gulf_simpl)
# Now read data for the Persian Gulf, which we need to get the distances for
# the extension of the map
PG <- readOGR(dsn = ".", "iho")
PG <- readShapePoly("iho.shp")
PG <- fortify(PG)
Run Code Online (Sandbox Code Playgroud)
现在,只需以正确的顺序绘制图层即可。
# generate plot
ggplot(sample.data) +
# first we plot the density...
stat_density_2d(aes(x = long, y = lat,
fill = ..level..),
geom="polygon",
alpha = 0.5) +
# ... then we plot the points
geom_point(aes(x = long, y = lat)) +
# gradient options
scale_fill_gradient(low = "green", high = "red") +
scale_alpha(range = c(0.00, 0.25), guide = FALSE) +
# and now put the shapes of the gulf states on top
geom_polygon(data = gulf_simpl_fort,
aes(x = long,
y = lat, group = group),
color = "black", fill = "white",
inherit.aes = F) +
# now, limit the displayed map only to the gulf
coord_equal(xlim = c(min(PG_fort$long), max(PG_fort$long)),
ylim = c(min(PG_fort$lat), max(PG_fort$lat))) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
390 次 |
| 最近记录: |