I recently started to work with R to display price forecast from firms and institutions (World Bank, EIA, Deloitte and Macquarie) for different products (USA Natural gas, Japan LNG and NBP gas).
So there is a graph displaying price forcast for the World Bank about USA Natural Gas, another graph for the World Bank about Japan LNG, another one for the World Bank about the NBP gas and so on with the EIA, Deloitte and Macquarie. So it's 12 graphs for now.
I had some trouble with paste
and sprintf
() functions but I managed to solve it.
Now I have a big final problem, beacause when I run the code, I get :
Error : ggplot2 doesn't know how to deal with data of class character
And I really don't know how to deal with it. Do you have any idea what is wrong with it? Thanks!
Here is the code :
chemin <- choose.files()
forecast <- data.frame(read.table(chemin, sep=";", dec=",", header=TRUE))
forecast$Publication.date <- as.Date(forecast$Publication.date, format="%d/%m/%Y")
forecast$Price.date <- as.Date(forecast$Price.date, format="%d/%m/%Y")
EIAforecast <- forecast[forecast$Forecaster=="EIA",]
WorldBankforecast <- forecast[forecast$Forecaster=="World Bank",]
Macquarieforecast <- forecast[forecast$Forecaster=="Macquarie",]
Deloitteforecast <- forecast[forecast$Forecaster=="Deloitte",]
library(ggplot2)
library(scales)
n <- 1
c1 <- c("USA", "Japan", "NBP")
c2 <- c("WorldBank", "EIA", "Deloitte", "Macquarie")
for (i in c1)
{
for (j in c2)
{
assign(sprintf("%srealizedprice", i), data.frame(read.table(paste("C:\\Travail\\Maxime\\Memoire\\Forecasts\\csv", paste0(i, "realizedprice.csv"), sep="\\"), sep=";", dec=",", header=TRUE)))
assign(sprintf("%srealizedprice$Date", i), as.Date(sprintf("%srealizedprice$Date", i), format="%d/%m/%Y"))
assign(sprintf("%srealizedpricegraph", i), ggplot(data=paste0(i, "realizedprice"), mapping=aes(x=Date, y=paste(i, "price", sep="."))) + geom_line())
assign(sprintf("%s%sforecast", i, j), paste(paste(paste0(j, "forecast"), paste0(j, "forecast$Price.type == "), sep="["), paste("\"Natural Gas", paste0(i, "\"]"), sep=", "), sep=""))
assign(sprintf("%sgraph", i), ggplot(data=get(paste0(i, j, "forecast")), aes(x=Price.date, y=Price, colour=as.character(paste(Price.type, Publication.date))))+geom_line()+geom_point()+geom_line(data = paste0(i, "realizedprice"), aes(x = Date, y = paste(i, "price", sep=".")), color = "cornflowerblue")+xlab('Date')+ylab('Price')+ggtitle(sprintf("World Bank forecast for Natural Gas %s", i)))
assign(sprintf("%sgraph", i), sprintf("%sgraph", i) + scale_x_date(breaks = date_breaks("year"),labels = date_format("%Y"))+scale_y_continuous(breaks = seq(0, 25, 1)))
mypath <- file.path(sprintf("C:\\Travail\\Maxime\\Memoire\\Forecasts\\Graphs\\Boucle\\%d.png", n))
paste0(i, "graph")
png(file=mypath)
plot(sprintf("%sgraph", i))
dev.off()
n <- n + 1
}
}