ggplot_stat_density2d 生态分布地块

ggplot_stat_density2d plots for ecological distribution

我正在尝试绘制我正在 Arabian/Persian 海湾研究的某些生物物种的生态分布图。这是我试过的代码示例:

背景层

library(ggplot2)
library(ggmap)

nc <- get_map("Persian Gulf", zoom = 6, maptype = 'terrain', language = "English")
ncmap <- ggmap(nc,  extent = "device")

其他图层

  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)

但是,我想使用 stat_density2d 来显示数百种物种(记录在列中,例如 SP1...SPn)在水体上的分布,而不仅仅是显示纬度和经度。

此外,是否可以将我的热图仅限于水体? 我会很感激我能得到的任何帮助和建议

我对你的问题的处理方法是务实的:只需将海湾国家层 放在 热图分布之上。这会相应地裁剪热图。但是请注意,热图 仍然按照未裁剪的方式进行计算。 这意味着密度计算 而非 仅限于水体只是,但它只是在视觉上被裁剪了。

为了可重现性,以下代码假定您已经解压缩了@Hammao 提供的 .rar 文件并在生成的 Persian Gulf 文件夹中执行代码。

# get sample data
sample.data <- read.csv("sample.data3.csv")

现在,我们需要获取海湾国家的国家形状。我为此使用 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)

现在,只需按照正确的顺序绘制图层即可。

# 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()