如何根据列设置alpha?

时间:2018-06-14 19:32:14

标签: r sp sf tmap

考虑这个例子:

library(dplyr)
library(sf)
library(tmap)

d <- data_frame(one = c(1,1,2,1,1,1,1),
                two = c(1,1,2,1,1,1,1))

std <- st_as_sf(d, coords = c('one', 'two'))

std %>% tm_shape() + tm_bubbles(alpha = 0.3)

$eq

您可以看到点(1, 1)较暗,因为它在数据中出现了6次。因此,由于alpha混合,这些点加起来。

我的问题是我无法存储数据集。我所拥有的只是一个聚合版本,比如

d_agg <- d %>% group_by(one, two) %>% 
  summarize(count = n()) %>% 
  ungroup()

# A tibble: 2 x 3
    one   two count
  <dbl> <dbl> <int>
1     1     1     6
2     2     2     1

如何使用d_agg和相应的count变量重现与之前完全相同的图表?

当然,重新创建上面的初始数据框是不可行的解决方案,因为我有太多的分数(并且有些点重复了太多次)

只需使用:

std_agg %>% tm_shape() + tm_bubbles(col = 'count', alpha = 0.3)

不起作用

enter image description here

2 个答案:

答案 0 :(得分:3)

不幸的是,alpha还不是美学,所以不可能alpha = "count"

我的问题:你真的需要阿尔法吗?如果你不使用颜色美学可能不会。在这种情况下,使用颜色来模拟alpha透明度的方法实际上很好,但只需要一点配置:

std_agg %>% tm_shape() + tm_bubbles(col = 'count', style = "cont", 
    palette =  "Greys", contrast = c(.3, .7), legend.col.show = FALSE)

enter image description here

答案 1 :(得分:1)

在此,我将展示如何使用d重新创建数据框dplyr。虽然它没有解决有关如何将数值传递给alpha中的tm_bubbles参数的问题,但请将其视为解决方法。

std_agg <- d_agg %>% 
  slice(rep(row_number(), times = count)) %>%
  st_as_sf(coords = c('one', 'two'))

std_agg %>% 
  tm_shape() + 
  tm_bubbles(alpha = 0.3)

enter image description here

事实上,扩展数据框架的这个基础R可能更直观。

d_agg[rep(1:nrow(d_agg), times = d_agg$count), ]
相关问题