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

时间:2017-05-10 15:40:46

标签: r ggplot2 gis contour shapefile

我使用核心密度估算生成了一张地图,我之前使用&b;生成了一个核心密度估算。功能来自kernsmooth包。我正在使用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

我想要做的是匹配密度表面颜色的下端和#39; ..级别。'对于其余的情节,所以当前显示为白色的东西都是深蓝色。这将使密度表面在整个图像上看起来是连续的,并且有效地将特定坐标处的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 个答案:

答案 0 :(得分: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

另外,删除col = "lightgrey"内的geom_polygon(aes(...)),或将其移到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