T
As pointed out in the comments, there are two problems in your data: 1) not all dates have values for all countries (indebted ones); 2) more than one value for the same country on the same date.Solution:convert your date. frame for wide format and then again for long format, so all dates are present for all countriesdo this using a function that adds duplicate valuesfill the missing values between dates with the value of the last filled cell (or with a linear interpolation, etc)convert the NAs at the beginning of the series of each country to 0I'm using the package date. table on a matter of personal preference. The same can be done with tidy or with reshape2 more basic R functions (approx, is.na, etc.).library(ggplot2)
library(data.table)
Carrega os dados como data.table
novo <- fread("dados.csv")
pode usar setDT(novo) para converter de data.frame para data.table
Converte para formato largo, agregando valores duplicados e preenchendo os ausentes com NA
gdados <- dcast(novo,
Commissioned ~ Country,
value.var = "somaacumulada",
fun = mean, # ou outra função mais relevante para seus dados
fill = NA)
ou reshape2::dcast ou tidyr::spread
pode usar também a ~ Country para ter linhas mais suaves, como no seu gráfico de exemplo
Converte de volta para formato longo
gdados <- melt(gdados,
id.vars = "Commissioned",
variable.name = "Country",
value.name = "somaacumulada")
ou reshape2::melt ou tidyr::gather
Converte datas para formato Date
gdados[, Commissioned := as.Date(Commissioned)]
Ordena os dados por país e data
setorder(gdados, Country, Commissioned)
Preenche os NAs subsequentes com o último valor presente
gdados[, acum := nafill(somaacumulada, type = "locf"), by = Country]
nafill faz parte do pacote data.table; verifique ?approx se estiver usando apenas o pacote base
Converte os NAs no início das séries para 0
gdados[, acum := nafill(acum, fill = 0), by = Country]
ou gdados[is.na(gdados)] <- 0 se usar o pacote base
ggplot(gdados, aes(Commissioned, acum, fill = Country)) +
geom_area() +
scale_x_date(date_breaks = "10 years",
date_labels = "%Y",
limits = c(as.Date("1939-01-01"), max(gdados$Commissioned))) +
labs(x = NULL, y = 'Potência Instalada [MW]', fill = NULL) +
theme_minimal()