- ### 声 明:本内容为作者借助R3.6.3和Rstudio及相关包制作而成,仅供学习交流,咨询交流加wx:huyanggs 或Email:huyanggs@hotmail.com
- ### 主 题:动态折线图 ·中国2000-2019年国内生产总值(GDP)及分产业变动
- ### 数据源:中国国家统计局·国家数据
- ### author:@拴小林Nobeli
- ### 时 间:2020/3/22
- # 1.loading packages
- library(ggplot2)
- library(readxl)
- library(av) #动态输出批量图为视频
- library(tidyr)
- # 2.读取数据和整理数据
- setwd("C:/Users/ysl/Desktop/")
- dt <- readxl::read_xlsx("C:/Users/ysl/Desktop/CHINA_GDP.xlsx")
- dt_s <- dt[,c(1,3:6)]
- # 3.转换数据结构+变量标签化
- dt_tidyr <- gather(dt_s, GDPs, value,-Year)
- dt_tidyr$GDPs <- factor(dt_tidyr$GDPs, levels = c("GDP", "First_GDP", "Second_GDP", "Third_GDP"),
- labels = c("国内生产总值(GDP·万亿)", "第一产业GDP(万亿)", "第二产业GDP(万亿) ", "第三产业GDP(万亿)"))
- # 3.将逐年数据批量print,并保存到自定义函数makeplot中
- # 注释:学习av包,可 ??av_demo 和 ??av_capture_graphics
- makeplot <- function(){
- dtlist <- NULL
- j = NULL
- for (i in 2000:max(dt_tidyr$Year)) {
- j = i-1999
- dtlist[[j]] <- dt_tidyr[dt_tidyr$Year %in% c(2000:i),]}
- lapply(dtlist, function(data){
- p <- ggplot(data, aes(x = Year, y = value, group = GDPs, color = GDPs, shape = GDPs)) +
- geom_point(labels = data$value) +
- geom_line(color = "grey") +
- scale_x_continuous(limits = range(dt_tidyr$Year)) +
- scale_y_continuous(limits = range(dt_tidyr$value)) +
- labs(x = "年份", y = "产值") +
- ggtitle("中国2000至2019年国内生产总值",
- subtitle = paste0(max(data$Year),"年国内生产总值",data[which(data$Year == max(data$Year)),][which(data[which(data$Year == max(data$Year)),]$GDPs == "国内生产总值(GDP·万亿)"),"value"],"万亿元")) +
- theme_classic() +
- theme(plot.title = element_text(color = "black", size = 16, vjust = 0.5,hjust = 0.5),
- legend.position = "bottom", legend.text = element_text(size = 8))
- print(p)
- })
- }
- # 4.将图片数据输出为视频
- # library(av)
- video_file <- file.path(getwd(), "output.mp4") #设置保存路径及文件名
- av_capture_graphics(makeplot(), video_file, 1280, 720, res = 144, vfilter = "framerate=fps=10") #参数意义可??av_capture_graphics学习
- av::av_media_info(video_file)
源数据及R代码:
链接:https://pan.baidu.com/s/1xn4Fq2DvMOTZMQAvrFAB1A
提取码:fj2a


雷达卡






京公网安备 11010802022788号







