首页 > 解决方案 > 为什么 ggplot 输出文件不再出现?

问题描述

在这个论坛的大量帮助下,过去几天我一直在生成 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)让我无法继续从事其他工作......

谢谢!

标签: rggplot2gganimate

解决方案


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

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 文件的前缀。


推荐阅读