如何在ggplot中使用两个不同的scale_fill_gradientn来分层两个geom_sf层?

yxyvkwin  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(169)

我有一个数据集,如下所示:

library(tidyverse)
library(sf)
library(giscoR)

temp <- data.frame(Country = c("United States", "Brazil", "Mexico", "Canada", "Argentina", "Chile",
                               "Peru", "Guatemala", 'Ecuador', "United Kingdom"),
                   Count = c(3000000, 300000, 250000, 135000, 100000, 99000, 98000, 47000, 40000, 39000))

我可以使用下面的代码成功地生成一个Map:

all_countries <- gisco_get_countries()
symbol_pos <- st_centroid(all_countries, of_largest_polygon = TRUE)
temp2 <- temp %>%
  left_join(symbol_pos, by=c("Country" = "NAME_ENGL")) %>%
  arrange(desc(Count))

ggplot() +
  geom_sf(data = all_countries, fill = "white") +
  geom_sf(data = temp2, pch = 21, mapping = aes(size = Count, geometry = geometry, fill = Count)) +  
  scale_size( range = c(1, 20), guide = guide_legend(direction = "horizontal", nrow = 1, label.position = "bottom")) +
  scale_fill_gradientn(colours = hcl.colors(10, "Blues 3", rev = TRUE, alpha = 0.9)) +
  guides(fill = guide_legend(title = "")) +
  theme_void() +
  theme(legend.position = "bottom")

我的主要问题是,美国的数字是如此之大,比其他所有的点都小得多,基本上是白色的。我真的很想有一个可视化,我可以有一个层与相同的确切代码,但删除美国的观察,然后是另一层美国的观测数据,但是红色的,其大小与第二大的巴西大致相同。所以它看起来像下面这样(但在US上有一个红色圆圈)

tempNoUS <- temp2 %>%
filter(Country != "United States")
ggplot() +
  geom_sf(data = all_countries, fill = "white") +
  geom_sf(data = tempNoUS, pch = 21, mapping = aes(size = Count, geometry = geometry, fill = Count)) +
  scale_size( range = c(1, 20), guide = guide_legend(direction = "horizontal", nrow = 1, label.position = "bottom")) +
  scale_fill_gradientn(colours = hcl.colors(10, "Blues 3", rev = TRUE, alpha = 0.9)) +
  guides(fill = guide_legend(title = "")) +
  theme_void() +
  theme(legend.position = "bottom")

我查看了library(ggnewscale),看看是否可以添加以下行作为测试的一部分:

+   new_scale("color") +
  geom_sf(data =temp2 %>% filter(Country == "United States"), pch = 21, mapping = aes(size = Count, geometry = geometry, fill = Count))

而且它似乎没有真正做任何事情。
总之,我想要两个geom_sf()层,一个用于非美国国家,scale_fill_gradientn为Blue3,另一个层仅用于美国,填充为Red。

qaxu7uf2

qaxu7uf21#

这就是你要找的吗?

ggplot() +
  geom_sf(data = all_countries, fill = "white") +
  geom_sf(data = tempNoUS, pch = 21, mapping = aes(size = Count, geometry = geometry, fill = Count)) +
  scale_size(range = c(1, 20), guide = guide_legend(direction = "horizontal", nrow = 1, label.position = "bottom")) +
  scale_fill_gradientn(colours = hcl.colors(10, "Blues 3", rev = TRUE, alpha = 0.9)) +
  guides(fill = guide_legend(title = "")) +
  new_scale("fill") +
  new_scale("size") +
  geom_sf(data =temp2 %>% 
            filter(Country == "United States"), pch = 21, 
          mapping = aes(size = Count, geometry = geometry, fill = Count)) +
  scale_fill_gradientn(colours = c("red")) +
  scale_size(range = c(1, 20)) +
  theme_void() +
  theme(legend.position = "right")

你可能需要调整图例的大小,比例限制来得到你想要的结果,听起来像是对计数进行对数转换,这样你就不需要分割数据了。

相关问题