首页 文章

为ggplot多边形的背景着色以匹配轮廓图层的较低值

提问于
浏览
0

我使用核密度估计生成了一个映射,我之前使用kernsmooth软件包中的'bkde2d'函数生成了该映射 . 我正在使用ggplot来绘制我的shapefile下的密度表面 . Test =我的数据框包含坐标值(IDLon和IDLat)以及内核密度估计(KDEst) . ScotMap.df是我的shapefile数据框 .

ggplot() +
  geom_contour(data=test, aes(x=IDLon, y=rev(IDLat), z=KDEst)) +
  stat_contour(data=test, geom="polygon", aes(x=IDLon, y=rev(IDLat), z=KDEst, fill=..level..)) +
  geom_polygon(data=ScotMap.df, aes(x=long,y=lat, group=group, col="lightgrey"), fill="lightgrey") +
  scale_x_continuous(limits = b[1,]) +
  scale_y_continuous(limits = b[2,]) +
  theme_bw()

产生这个情节:

enter image description here

我想要做的是将密度表面颜色的下端从“..水平......”与图的其余部分相匹配,这样当前显示为白色的所有东西都是深蓝色 . 这将使密度表面在整个图像上看起来是连续的,并且有效地将特定坐标处的0值指定为与下端值相同的颜色 . 我尝试通过手动匹配颜色来捏造颜色,但颜色调色板上的任何内容都不相同,所以我能做的最好的是:

ggplot() +
  geom_contour(data=test, aes(x=IDLon, y=rev(IDLat), z=KDEst)) +
  stat_contour(data=test, geom="polygon", aes(x=IDLon, y=rev(IDLat), z=KDEst, fill=..level..)) +
  geom_polygon(data=ScotMap.df, aes(x=long,y=lat, group=group, col="lightgrey"), fill="lightgrey") +
  scale_x_continuous(limits = b[1,]) +
  scale_y_continuous(limits = b[2,]) +
  theme_bw() +
  theme(panel.background = element_rect(fill = "blue4"))

enter image description here

有任何想法吗?

1 回答

  • 1

    In the documentation for scale_fill_gradient比例的最低值是 low = "#132B43" ,而最高值是 high = "#56B1F7" .

    data_frame(x = sample(1:5, 5), y = sample(1:5, 5), z = rnorm(5)) %>% 
      ggplot(aes(x, y, fill = z)) + geom_tile(width = 1, height = 1, colour = "white") + 
      theme(panel.background = element_rect(fill = "#132B43"))
    

    enter image description here

    另外,删除 geom_polygon(aes(...)) 内的 col = "lightgrey" ,或将其移到 aes(...) 之外,以摆脱额外的图例条目(这也是为什么它会出现错误的颜色) .

    编辑:

    require(scales)
    data_frame(x = sample(1:5, 5), y = sample(1:5, 5), z = rnorm(5)) %>% 
      ggplot(aes(x, y, fill = z)) + geom_tile(width = 1, height = 1, colour = "white") + 
      scale_fill_distiller(type = "seq", palette = "YlGnBu") +
      theme(panel.background = element_rect(fill = brewer_pal(type = "seq", palette = "YlGnBu")(6)[6]))
    

    enter image description here

    require(viridis)
        data_frame(x = sample(1:5, 5), y = sample(1:5, 5), z = rnorm(5)) %>% 
          ggplot(aes(x, y, fill = z)) + geom_tile(width = 1, height = 1, colour = "white") + 
          scale_fill_viridis() +
          theme(panel.background = element_rect(fill = viridis_pal()(6)[1]))
    

    enter image description here

相关问题