library(data.table)
library(ggplot2)
library(tidyverse)
library(tidyr)
library(scales)
library(ggiraph)
library(lubridate)
## Read and clean data
stocksall <- fread("~/stocks/stocksall.csv", sep = ",", header = TRUE)
stocksall <- unique(stocksall)
oldstocks <- fread("~/stocks/pdsold.csv", sep = ",", header = TRUE)
oldstocks[, coarsegrains := stocks_total - stocks_rice - stocks_wheat]
## Melt stocksall to long format
t <- melt(stocksall, id = c("Year", "Commodity"))
## Convert to Date
t[, Date := as.Date(paste("01", variable, Year, sep = "-"), "%d-%b-%Y")]
t[, Commodity := factor(Commodity, levels = c("Rice", "Wheat", "Unmilled Paddy", "Coarsegrain", "Total"))]
## Process oldstocks
oldstocks <- separate(oldstocks, col = Year, sep = "-", into = c("v1", "year"))
setDT(oldstocks)
oldstocks[, Date := as.Date(paste("01", "04", year, sep = "-"), "%d-%m-%y")]
oldstocks <- oldstocks[Date < as.Date("2003-01-01"),
.(Date, Rice = stocks_rice, Wheat = stocks_wheat, Coarsegrain = coarsegrains)]
t1 <- melt(oldstocks, id = "Date")
t1[, value := value * 10] ## Convert to lakh tonnes
setnames(t1, "variable", "Commodity")
## Filter and combine
t_filtered <- t[Commodity != "Total", .(Date, Commodity, value)]
t_filtered <- t_filtered[!is.na(value)]
t1 <- t1[!is.na(value)]
combined <- rbind(t_filtered, t1)
combined[, value := as.numeric(value) / 10] ## Convert to million tonnes
combined <- combined[!is.na(value)]
## Create stacked data for area plot
stacked_data <- combined[order(Commodity, Date)]
stacked_data[, Commodity := factor(Commodity,
levels = rev(c("Rice", "Wheat", "Unmilled Paddy", "Coarsegrain")))]
## Calculate cumulative sum for stacking
setorder(stacked_data, Date, Commodity)
stacked_data[, cum_value := cumsum(value), by = Date]
## Create tooltip for interactivity
stacked_data[, tooltip := paste0(
"Date: ", format(Date, "%b %Y"), "\n",
"Commodity: ", Commodity, "\n",
"Stock: ", round(value, 1), " million tonnes\n",
"Percentage: ", round(value/sum(value)*100, 1), "%"
), by = Date]
## Custom theme
my_theme <- theme_bw(base_size = 14) +
theme(
text = element_text(family = "sans", color = "#333333"),
plot.title = element_text(size = 18, face = "bold", hjust = 0.5,
margin = margin(10, 0, 10, 0)),
plot.subtitle = element_text(size = 12, hjust = 0.5, color = "#666666"),
axis.title = element_text(size = 14),
axis.text = element_text(size = 12),
legend.position = "bottom",
legend.title = element_blank(),
legend.text = element_text(size = 11),
panel.grid.major = element_line(color = "#F0F0F0", linewidth = 0.5),
panel.grid.minor = element_blank(),
panel.border = element_rect(color = "#CCCCCC", fill = NA, linewidth = 0.8),
axis.line = element_line(color = "#333333", linewidth = 0.5),
axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
plot.caption = element_text(size = 10, color = "#666666", hjust = 0)
)