ggplot/ggimage 中带有圆形国旗符号的气泡图

Bubble chart with round country flag symbols in ggplot/ggimage

我尝试通过包含国旗来制作带有 ggplot/ggimage 的气泡图。这是一个可重现的例子:

library(dplyr)
library(ggplot)
library(ggimage)

A <- data.frame(X = c(1,4,5), Y = c(10, 1, 5), Z = c(1, 2, 3)/30, Country = c("FR", "BE", "IT"), CountryFlag = paste0("https://flagcdn.com/h20/", str_to_lower(Country), ".png"))

A_plot <- ggplot(A, mapping = aes(x = X, y = Y, size = I(Z), image = CountryFlag)) +
          geom_image()

X11(); print(A_plot)

除了下载圆形旗帜外,是否可以将旗帜转换为圆形,或者是否可以将国家/地区插入气泡中。我尝试了以下代码,但它不起作用:

library(dplyr)
library(ggplot)
library(ggimage)

A <- data.frame(X = c(1,4,5), Y = c(10, 1, 5), Z = c(1, 2, 3), Country = c("FR", "BE", "IT"), CountryFlag = paste0("https://flagcdn.com/h20/", str_to_lower(Country), ".png"))

A_plot <- ggplot(A, mapping = aes(x = X, y = Y, size = Z, image = CountryFlag)) +
          geom_point(alpha = 0.5, col = "lightblue") +
          geom_image()

X11(); print(A_plot)

我收到错误:

Error in `[<-`(`*tmp*`, !is.na(alpha), 4, value = alpha[!is.na(alpha)]) : 
  (subscript) logical subscript too long
In addition: Warning message:
In rep(colour, length.out = length(alpha)) :
  'x' is NULL so the result will be NULL

欢迎提出任何建议。

这是一个为每个标志添加圆形掩码的函数。如果我们从你的情节开始,

A_plot

我们获取 url 并创建一些本地文件名:

flags <- A_plot$data$CountryFlag
png_files <- sapply(strsplit(flags, "/"), function(x) x[length(x)])

现在我们创建一些带有圆形遮罩的图像并将它们保存在本地:

OK <- Map(function(flag, png) {
  im <- magick::image_read(flag)
  im <- magick::image_resize(im, magick::geometry_size_percent(500, 2000))
  ii <- magick::image_info(im)
  width <- ii$width
  fig <- magick::image_draw(magick::image_blank(height, height))
  symbols(width/2, width/2, circles=(width/2), bg='black', inches=FALSE, add=TRUE)
  im2 <- magick::image_composite(im, fig, operator='copyopacity')
  magick::image_write(im2, png)
}, flag = flags, png = png_files)

现在将这些文件路径写入绘图对象中作为我们的图像位置:

A_plot$data$CountryFlag <- png_files

将我们的情节更改为:

A_plot

为了完整起见,我们应该在绘制完剧情后自己整理一下:

sapply(png_files, unlink)

有趣的是, which pointed to a package for an easy way to get exactly what you want. The {ggflags} package (not on CRAN!) introduces geom_flag, which uses readily available round flag icons from the EmojiOne set作为积分。

library(tidyverse)
# devtools::install_github("jimjam-slam/ggflags")
library(ggflags)

Country <- c("FR", "BE", "IT")

A <- data.frame(
  X = c(1, 4, 5), Y = c(10, 1, 5), Z = c(1, 2, 3), Country = tolower(Country))

ggplot(A, mapping = aes(x = X, y = Y, size = Z*3, country = Country)) +
  geom_flag()+
  # you can then set the scale as usual by using scale_size
  scale_size_identity(guide = guide_legend())

reprex package (v2.0.1)

创建于 2022-04-03