如何使用ggplot绘制海洋温度图?

时间:2020-01-28 20:21:23

标签: r ggplot2

我正在尝试制作一张贴在上面的地图,如上图。基本上,我希望海岸线呈灰色,海洋要具有与我作为csv文件导入的某些温度数据有关的颜色比例 enter image description here

数据框看起来像这样


     Longitude   Latitude    Temp     month
1   -64.49677   43.29375    6.760617    M1
2   -64.49677   43.29375    4.384344    M1
3   -64.49677   43.29375    4.384344    M1
4   -64.49677   43.29375    5.736011    M2
5   -64.49677   43.29375    4.004751    M2
6   -64.49677   43.29375    4.004751    M2
7   -64.49677   43.29375    6.139031    M3
8   -64.49677   43.29375    4.358370    M3
9   -64.49677   43.29375    4.358370    M3
10  -64.49677   43.29375    4.931975    M4
11  -64.49677   43.29375    3.564750    M4
12  -64.49677   43.29375    3.564750    M4
13  -64.49677   43.29375    5.227865    M5
14  -64.49677   43.29375    4.619469    M5
15  -64.49677   43.29375    4.619469    M5
sample = structure(list(Longitude = c(-64.4619750976563, -64.46533203125, 
-64.4687118530274, -64.4721221923828, -64.4755630493164, -64.4790267944336
), Latitude = c(42.7215003967285, 42.7790260314941, 42.836483001709, 
42.8938713073731, 42.9511947631836, 43.0084533691406), Temp = c(6.62386226654053, 
7.07512044906616, 7.37884569168091, 7.49466228485107, 7.50688648223877, 
7.53506231307983), month = c("M1", "M1", "M1", "M1", "M1", "M1"
)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"), groups = structure(list(month = "M1", .rows = list(
    1:6)), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame"), .drop = TRUE))

到目前为止,我已经使用以下代码导入了地图并创建了以下图片

ggplot(mapoc_temp, aes(x=Longitude, y=Latitude)) + 
  stat_density2d(aes(fill = ..level..), alpha=0.5, geom="polygon") +
  geom_path(data=canada,aes(x=long, y=lat,group=group), colour="grey50")+
  scale_fill_gradientn(colours=rev(brewer.pal(7,"Spectral")))+
  coord_sf(xlim=c(-64.5,-62.8), ylim=c(42.7,45), expand = FALSE)

enter image description here

如您所见,这张地图看起来与其他图片完全不同,海岸线是彩色的。有没有人建议如何将一些温度数据映射到地图上?

1 个答案:

答案 0 :(得分:2)

您的问题不能完全重现,但是我取了一些数据from your previous question

我认为您可以“安全地”忽略使用geom_raster的警告,并将其与interpolate = TRUE一起使用

此外,在绘制如下所示的“完整”栅格时,我没有得到警告。

以下显示了如何避免海岸显示颜色,非常简单,只需在栅格上方绘制地图,但使用geom_polygon进行填充即可。因为您只提供了6个温度数据点,所以我创建了一些虚假数据-根据测量的密度,这看起来或多或少都是颗粒状的

library(mapdata)
#> Loading required package: maps
library(tidyverse) 

canada <- map_data("worldHires", "Canada")

sample_df <- expand.grid(data.frame(Longitude= seq(-64.5,-62.4,0.1), Latitude= seq(42.7,44.8,0.1)))
sample_df$Temp <- runif(nrow(sample_df))
#requires sf package
ggplot(sample_df, aes(x=Longitude, y=Latitude)) + 
  geom_raster(aes(fill = Temp, x = Longitude), interpolate = TRUE) +
  geom_polygon(data = canada, aes(x=long, y=lat, group=group), colour="grey50", fill = 'grey55')+
  coord_sf(xlim=c(-64.5,-62.8), ylim=c(42.7,45))

reprex package(v0.3.0)于2020-01-28创建