为什么 ggplot 输出文件不再出现?

why are ggplot output files no longer appearing?

在这个论坛的大力帮助下,过去几天我一直在为工作生成 covid-19 数据的动画地图。减去我办公室要求的一些叠加层,我使用的基本脚本是

library(urbnmapr) # For map
library(ggplot2)  # For map
library(dplyr)    # For summarizing
library(tidyr)    # For reshaping
library(stringr)  # For padding leading zeros
library(ggrepel)
library(ggmap)
library(usmap)
library(gganimate)
library(magrittr)
library(gifski)

# Get COVID cases, available from:
url <- "https://static.usafacts.org/public/data/covid-19/covid_confirmed_usafacts.csv"
COV <- read.csv(url, stringsAsFactors = FALSE)

Covid <- pivot_longer(COV, cols=starts_with("X"),
                      values_to="cases",
                      names_to=c("X","date_infected"),
                      names_sep="X") %>%
  mutate(infected = as.Date(date_infected, format="%m.%d.%Y"),
         countyFIPS = str_pad(as.character(countyFIPS), 5, pad="0"))

# Obtain map data for counties (to link with covid data) and states (for showing borders)
states_sf <- get_urbn_map(map = "states", sf = TRUE)
counties_sf <- get_urbn_map(map = "counties", sf = TRUE)

# Merge county map with total cases of cov
counties_cov <- inner_join(counties_sf, Covid, by=c("county_fips"="countyFIPS"))

setwd("C:/mypath")
p <- counties_cov %>%
  ggplot() +
  geom_sf(mapping = aes(fill = cases), color = NA) +
  geom_sf(data = states_sf, fill = NA, color = "black", size = 0.25) +
  coord_sf(datum = NA) +   
  scale_fill_gradient(name = "Cases", trans = "log", low='green', high='red',
                      na.value = "white",
                      breaks=c(1, max(counties_cov$cases))) +
  theme_bw() + 
    theme(legend.position="bottom", 
        panel.border = element_blank(),
        axis.title.x=element_blank(), 
        axis.title.y=element_blank())

print(p + transition_time(infected) + 
        labs(title='Confirmed COVID-19 Cases: {frame_time}'))

png_files <- list.files("C:/mypath", pattern = ".*png$", full.names = TRUE)
st = format(Sys.time(), "%Y-%m-%d")
gifName <- paste("COVID-19-Cases-byCounty_",st,".gif",sep="")
gifski(png_files, gif_file = gifName, width = 800, height = 600, delay = 0.25, loop=FALSE)

这一直很有效。在我的笔记本电脑上大约需要 30 分钟,但完成后我有 ~100 个代表每天数据的 .png 文件和位于工作目录中的将它们拼接在一起的动画 gif。

今天早些时候我更新了包...没有太在意,只是使用 RStudio 包管理器检查更新并说全部更新。

首先我得到一个错误

Error: stat_sf requires the following missing aesthetics: geometry

我想我通过更改

解决了这个问题
geom_sf(mapping = aes(fill = cases), color = NA) +

geom_sf(mapping = aes(fill = cases, geometry=geometry), color = NA) +

现在脚本运行了,我得到了我以前见过的渲染进度条。 RStudio 查看器中甚至还有一张动画地图,但是工作目录中没有出现 .png 文件,因此 gifski 没有任何东西可以从中构建 gif。

我需要做什么才能取回输出文件?这是 a) 让我觉得自己很愚蠢,b) 让我无法继续从事其他工作...

谢谢!

您必须保存动画的帧而不是简单地打印。试试这个:

a <- p + transition_time(infected) + 
            labs(title='Confirmed COVID-19 Cases: {frame_time}')

animate(a, nframes = 24, device = "png", renderer = file_renderer("C:/mypath", prefix = "gganim_plot", overwrite = TRUE))

使用参数 nframes 可以设置帧数,使用 prefix 可以设置 png 文件的前缀。