【问题标题】:the borders function in ggplot did not work as expected?ggplot 中的边框功能没有按预期工作?
【发布时间】:2019-06-06 16:29:14
【问题描述】:

我想绘制两个变量之间的(空间)相关模式并被国家边界重叠。我将borders() 函数与 ggplot 一起使用,但 xlim 和 ylim 没有给出我期望的确切限制,相反,它们给出了整个国家。我希望有确切的限制来重叠数据。

 library(ncdf4)
 library(ggplot2)
 library(reshape)
 library(maps)
 library(stringr)
 library(reshape2)
 library(mapdata)
 library(maptools)
 ncfile <-   nc_open("/Volumes/KIT/CHIRPS/index/correlation/correlation.amm.allindex.nc")

 lon <- ncvar_get(ncfile, "lon")
 lat <- ncvar_get(ncfile, "lat")
 pr <- ncvar_get(ncfile, "prptotcorrel")
 ret <- list ("lat"=lat, "lon"=lon,"pr"= pr)
 ##
 str(ret)
 ######## melt function for pr
 melt_pr <- function(L) {
 dimnames(L$pr) <- list(lon = L$lon, lat = L$lat)
 rett <- melt(L$pr, value.name ="pr") 
  }
  ######
  mpr <- melt_pr(ret)
  head(mpr)
  #
  xlims=range(mpr$lon); xlims
  ylims=range(mpr$lat); ylims

  gcorrelation=ggplot(data = mpr, aes(x = lon, y = lat, fill = pr)) + 
  geom_tile() +
  borders('world', xlim=xlims, ylim=ylims, colour='black', size=.2) +
  coord_fixed(xlim=xlims, ylim=ylims) +
  labs(x = "Longitude", y = "Latitude") +
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                   midpoint = 0, limit = c(-1,1), na.value = NA,        name="correlation") +
   theme_bw() +
   coord_fixed(1.3) 
   gcorrelation

我希望有与数据完全吻合的国家边界。 这是我希望情节看起来的样子。这是国家/地区的图像;我只想与阴影数据的确切限制重叠。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    欢迎来到堆栈溢出。如果没有数据样本 (as code),将很难提供帮助。我相信coord_cartesian() 会做你想做的,而不是coord_fixed()

    【讨论】:

      【解决方案2】:

      不要使用coord_fixed()coord_cartesian(),而是使用coord_map()xlimylim 参数。

      coord_map() 使用 mapproj 包定义的任何投影将地球的一部分(近似球形)投影到平面 2D 平面上。

      (正如@yake84 建议的那样,最好提供包含代码和数据的问题的简化版本,以便人们可以运行和测试他们的解决方案。)


      退后一步,如果您正在开发新代码,我会避免使用过时的包,如 reshapereshape2 和一些空间函数。而是建立在它们的替代品(通常由同一个人开发)上,例如 tidyrsf,以及 ggplot2 中的相关函数,例如 ggsf()

      【讨论】:

        【解决方案3】:

        嗨@yake84 和@wibeasley,对不起,我对堆栈溢出很陌生,感谢您的建议,coord_map() 给出了正确的预期地图。也感谢软件包的建议。

        【讨论】:

          猜你喜欢
          • 2021-12-26
          • 2015-02-23
          • 1970-01-01
          • 1970-01-01
          • 2012-05-26
          • 2021-01-08
          • 2021-02-25
          • 1970-01-01
          • 2013-04-28
          相关资源
          最近更新 更多