我正在尝试创建一个包含一些负值和大部分为正值的地图。我拥有的代码(如下所示)会生成正确的地图,但是图例未居中于0(即白色不在0处,而更多的负值更深的红色和更多的正值更蓝色)。无论数据集中的值如何,如何将调色板更改为以0为中心?
代码:
library(tidyverse)
library(sf)
library(mapview)
palfunc <- function (n, alpha = 1, begin = 0, end = 1, direction = 1)
{
colors <- RColorBrewer::brewer.pal(11, "RdBu")
if (direction < 0) colors <- rev(colors)
colorRampPalette(colors, alpha = alpha)(n)
}
foo <- franconia %>% mutate(foo = rnorm(n()) + 2)
max_val = max(abs(foo$foo), na.rm = T)
n_val = max( length(unique(keep(foo$foo, ~.x > 0))),
length(unique(keep(foo$foo, ~.x < 0))))
at = lattice::do.breaks(endpoints = c(-max_val, max_val), nint = 2 * n_val + 1)
p <- mapView(foo, zcol = 'foo', layer.name = "Example", col.regions = palfunc, at = at)
答案 0 :(得分:1)
看来r-mapview
的{{1}}变量不能处理超过10个中断。看下面:
at
library(tidyverse)
library(sf)
library(mapview)
palfunc <- function (n, alpha = 1, begin = 0, end = 1, direction = 1)
{
colors <- RColorBrewer::brewer.pal(11, "RdBu")
if (direction < 0) colors <- rev(colors)
colorRampPalette(colors, alpha = alpha)(n)
}
set.seed(92)
foo <- franconia %>% mutate(foo = rnorm(n()) + 2)
max_val = max(abs(foo$foo), na.rm = T)
n_val = max( length(unique(keep(foo$foo, ~.x > 0))),
length(unique(keep(foo$foo, ~.x < 0))))
at_10 = lattice::do.breaks(endpoints = c(-max_val, max_val), nint = 10)
mapView(foo, zcol = 'foo', layer.name = "Example", col.regions = palfunc, at = at_10)
但是,如果我们实际上具有负值(at_11 = lattice::do.breaks(endpoints = c(-max_val, max_val), nint = 11)
mapView(foo, zcol = 'foo', layer.name = "Example", col.regions = palfunc, at = at_11)
),则图例默认情况下将以0为中心:
min(values) ≈ max(values)
因此,我解决问题的方法是在library(tidyverse)
library(sf)
library(mapview)
palfunc <- function (n, alpha = 1, begin = 0, end = 1, direction = 1)
{
colors <- RColorBrewer::brewer.pal(11, "RdBu")
if (direction < 0) colors <- rev(colors)
colorRampPalette(colors, alpha = alpha)(n)
}
set.seed(92)
foo <- franconia %>% mutate(foo = c((rnorm((n()-1)) + 2), -4))
max_val = max(abs(foo$foo), na.rm = T)
n_val = max( length(unique(keep(foo$foo, ~.x > 0))),
length(unique(keep(foo$foo, ~.x < 0))))
mapView(foo, zcol = 'foo', layer.name = "Example", col.regions = palfunc)
和foo
的{{1}}数据中添加两行,它们基本上是-max_val
,没有面积和长度( aka点),因此我们的数据集的镜像值在零附近,因此+max_val
会生成“平衡”图例,但是用户不会在地图上看到这些点,因为它们的面积为零。再次在下面查找骇客的实现。 (ps:如果您愿意,可以在数据边界之外的某个位置添加这些虚拟点/多边形,然后将默认缩放比例设置为实际数据,这是不必要的,因为正如我所说,这些虚拟点不可见)。 / p>
multipolygons
由reprex package(v0.3.0)于2019-06-25创建