Добро пожаловать в третье издание основ GGplot. В этом модуле мы познакомимся с анимацией и созданием GIF-файлов, а также создадим график HD-качества с помощью функции анимации.

О наборе данных

ВВП Индии 1960–2022 гг .: Данные о ВВП Индии с 1960 по 2022 г.

ВВП в ценах покупателя представляет собой сумму валовой добавленной стоимости всех производителей-резидентов в экономике плюс любые налоги на продукты и минус любые субсидии, не включенные в стоимость продуктов. Он рассчитывается без вычетов на амортизацию произведенных активов или истощение и деградацию природных ресурсов.

Лицензия

CC0: Общественное достояние

Ожидаемая частота обновлений

Ежегодно

ИСТОЧНИКИ

https://www.macrotrends.net/countries/IND/india/gdp-gross-domestic-product

МЕТОДОЛОГИЯ СБОРА

С помощью веб-скрейпинга с помощью pandas.

Ожидаемое обновление

Ежегодно (обновлено 20 дней назад)

Импорт набора данных

#Input

India_gdp <- read.csv("C:/Users/AMBUJ SHUKLA/Downloads/India_gdp.csv")
 View(India_gdp)

Изменение имени столбца с «Рост %» на «Рост_процент»

#Input

names(India_gdp)[5] <- 'Growth_percent'
 head(India_gdp)
#Output

 Serial Year GDP.in..Billion... Per.Capita.in.rupees Growth_percent
1      0 2021            3173.40               182160           8.95
2      1 2020            2667.69               154640          -6.60
3      2 2019            2831.55               165760           3.74
4      3 2018            2702.93               159840           6.45
5      4 2017            2651.47               158480           6.80
6      5 2016            2294.80               138640           8.26
> 

Импорт библиотек:

 library(ggplot2)
 library(readxl)
 library(tidyverse)
 library(gganimate)
 library(ggthemes)

График данных:

 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line()

Добавление точки geom_point на график.

 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line()+geom_point()

Добавление заголовка, цвета к линии геометрии, точки геометрии и изменение размеров точек:

 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+geom_point(color = "#1874CD", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")

Добавление сглаживания геометрии для лучшего понимания линии тренда:

 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+
   geom_point(color = "#1874CD", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
   geom_smooth(size = 1, method = "loess", se=FALSE)

Добавление функции geom_smooth() добавляет линию тренда поверх существующего графика. Я использую лессовую регрессию вместо линейной регрессии, чтобы понять сложную скользящую среднюю и найти кривую, которая соответствует всем точкам.

Мне нужно зафиксировать диапазон (ось x, ось y), нужно растянуть его, чтобы получить четкое представление о линии тренда, следующей каждые 10 лет, а не 20 лет диапазона по оси x и от -10 до 10 по оси y.

 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+
   geom_point(color = "#E0EEE0", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
   geom_smooth(size = 0.4, method = "loess", se=FALSE, color ="#FF7256" )+
   scale_x_continuous(breaks=seq(1960,2022,10))+
   scale_y_continuous(breaks=seq(-10, 10, 2))

Я использовал цветовую палитру из R Charts: Link

Использование темной темы для изменения темы сюжета.

 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+
   geom_point(color = "#E0EEE0", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
   geom_smooth(size = 0.4, method = "loess", se=FALSE, color ="#FF7256" )+
   scale_x_continuous(breaks=seq(1960,2022,10))+
   scale_y_continuous(breaks=seq(-10, 10, 2))+
   theme_solarized_2(light=F)

Анимация

Основная часть, т. е. статический сюжет, готова, теперь нам нужно анимировать его с помощью функции перехода в режим показа(). Этот переход позволяет нам постепенно отображать данные в зависимости от заданного временного измерения. Здесь нашим измерением времени является год.

ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.7)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  theme_solarized_2(light=F)+
  transition_reveal(Year)

Я собираюсь добавить фиксацию оси Y к ее положению и позволить оси X корректироваться входящим набором данных с помощью view_follow

Добавление заголовка вверху с изменением лет по мере изменения данных с использованием frame_along с использованием функции ggtitle {(frame_along)}.

Добавление функции анимации для настройки качества производства с лучшим FPS, разрешением и скоростью.

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.7)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=30)

Регулировка разрешения и кадров в секунду в функции анимации. nframes=400, разрешение 180

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.4)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=400, width = 1280, height = 720, res = 180, fps = 60)

Давайте поднимем его на следующий уровень для лучшего качества:

Помните: поскольку FPS, разрешение и количество кадров, связанных вместе, увеличиваются, время рендеринга также увеличивается, что может потребовать времени для компиляции визуализации.

Увеличение кадров до 600 и разрешение до 200

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.4)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=600, width = 1280, height = 720, res = 200, fps = 60)

Удаление темного режима, чтобы визуализация ощущалась в светлом режиме:

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.4)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=600, width = 1280, height = 720, res = 200, fps = 60)

Консоль:

#Importing dataset

India_gdp <- read.csv("C:/Users/AMBUJ SHUKLA/Downloads/India_gdp.csv")
 View(India_gdp)


 #Creating animation of line chart from dataset of Indias GDP from 1960-2022
 
 #Importing libraries 
 
 library(ggplot2)
 library(readxl)
 library(tidyverse)
 library(gganimate)
 library(ggthemes)
 
 # Changing the column name
 
 names(India_gdp)[5] <- 'Growth_percent'
 head(India_gdp)
 
 #plotting the static data with geomline
 
 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line()
 
 #adding geompoint in the plot
 
 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line()+geom_point()
 
 
#Adding title, color and subitles in the axis.
 
 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+geom_point(color = "#1874CD", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")
 
 #Adding geom_smooth() adds a trend line over an existing plot. I am using loess regression instead of 
 #linear regression to understand complicated moving average to find a curve which fits all the point.
 
 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+
   geom_point(color = "#1874CD", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
   geom_smooth(size = 0.6, method = "loess", se=FALSE)
 
 
 #I need to fix X -Y axis, need to stretch it wide to get clear view of trend line following year, adding 
 #dark theme using solarized function
 
 ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+
   geom_point(color = "#E0EEE0", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
   geom_smooth(size = 0.4, method = "loess", se=FALSE, color ="#FF7256" )+
   scale_x_continuous(breaks=seq(1960,2022,10))+
   scale_y_continuous(breaks=seq(-10, 10, 2))+
   theme_solarized_2(light=F)
 
 #333 It's time to add frames and animation to the plot
 
ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
   geom_line(color = "#00BFFF", size = 0.7)+
   geom_point(color = "#E0EEE0", size = 0.99)+
   ggtitle("GDP growth of India year-wise from 1960 to 2022")+
   labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
   geom_smooth(size = 0.4, method = "loess", se=FALSE, color ="#FF7256" )+
   scale_x_continuous(breaks=seq(1960,2022,10))+
   scale_y_continuous(breaks=seq(-10, 10, 2))+
   theme_solarized_2(light=F)

#222 It's time to add frames and animation to the plot
ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.7)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  theme_solarized_2(light=F)+
  transition_reveal(Year)
  
  #111 I am going to add fix the y axis to its position and let the x axis adjust with incoming set of data.

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.7)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)
 anim_gdp


#Adding title on the top with changing years as the data progresses using frame_along under ggtitle 
#and also adding animation function to control the frames and make viz more appealing

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.7)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

anim_gdp


#adding animate fuction to tweak quality of production

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.7)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=30)

#improving the quality of the gif under animate () function

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.4)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=400, width = 1280, height = 720, res = 180, fps = 60)

#increasing the frames to 600

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.4)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  theme_solarized_2(light=F)+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=600, width = 1280, height = 720, res = 200, fps = 60)


#rendering time was almost 3 mins bt the quality of plot is awsome.

#Removing dark mode

anim_gdp<-ggplot(data = India_gdp, mapping = aes(x=Year, y =Growth_percent ))+
  geom_line(color = "#00BFFF", size = 0.4)+
  geom_point(color = "#E0EEE0", size = 0.99)+
  ggtitle("GDP growth of India year-wise from 1960 to 2022")+
  labs(x= "Year", y= "GDP Growth in Percentage", title = "GDP Growth of India from 1960 to 2022")+
  scale_x_continuous(breaks=seq(1960,2022,10))+
  scale_y_continuous(breaks=seq(-10, 10, 2))+
  ggtitle("India's GDP in {(frame_along)}")+
  transition_reveal(Year)+
  view_follow(fixed_y=T)

animate(anim_gdp, nframes=600, width = 1280, height = 720, res = 200, fps = 60)

Мы продолжим эту версию подробно в следующей части этого проекта. Надеюсь, у вас все хорошо. Спасибо! 😊

Больше контента наmedium.com/r-evolution. Следите за нами в Twitter и подпишитесь на нашу бесплатную еженедельную рассылку новостей.