如何根据列设置 alpha?

How to set the alpha based on a column?

考虑这个例子:

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)

可以看到点(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 变量重现与以前完全相同的图表?

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

正在使用:

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

无效

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

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)

其实这个base R扩展data frame大概更直观

d_agg[rep(1:nrow(d_agg), times = d_agg$count), ]

不幸的是,alpha(还)不是一种审美,所以不可能alpha = "count"

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

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