steve steve - 3 months ago 13
R Question

ggplot2 - Insert title using file names

I need to plot several tables, in order to automatize the process, I would like to use the files names and insert it as the title for each plots.

For example, the file names has the following naming scheme:

almourol_gfdl-esm2m_rcp8p5_daily_ref.csv


My desired output, should looks like that:

Almourol daily discharge ref. period


For the moment I am using the following code:

almourol_ref <- read.table("almourol_gfdl-esm2m_rcp8p5_daily_ref.csv", header = TRUE, sep = ";", fill = TRUE)
library(ggplot2)
library(reshape2)
library(tools)
title = file_path_sans_ext("almourol_gfdl-esm2m_rcp8p5_daily_ref.csv")
title = strsplit(title, "_")
title = noquote(title)
title = paste(title[1],title[4], "discharge",title[5], period)
almourol_ref <- melt(almourol_ref, id.vars="DAYS")
png("almourol_ref.png", width = 600, height = 400)
p <- ggplot(almourol_ref, aes(DAYS,value, col=variable))
p + geom_line(size = 0.1) +
geom_hline(aes(yintercept = 0), linetype="dotted") +
ylab("Runoff [m3/s]") +
xlab("Day") +
theme_bw() +
theme(legend.key = element_blank())+
scale_color_discrete(name='Models GCM_HM') +
ggtitle(title)


Unfortunately it does not work and any title is added to the graphs. Any ideas or hints are more than welcome.

Please find a minimal example of the data:

DAYS;GWFDisi;GSWIM;GGAP3;GHYPE;GVIC;HWFDisi;HSWIM;HGAP3;HHYPE;HVIC;IWFDisi
1;-308.78;-183.19;-232.48;-233.22;-150.38;-596.49;-311.58;-571.41;-387.63;-315.43;-451.26
2;-348.52;-192.39;-314.68;-231.67;-147.88;-563.14;-335.39;-558.46;-423.13;-355.14;-501.58
3;-416.24;-211.68;-436.83;-232.73;-164.87;-537.54;-327.19;-465.70;-455.62;-403.40;-458.43
4;-459.95;-217.75;-486.37;-228.07;-202.23;-560.68;-359.07;-497.20;-481.41;-430.87;-475.76
5;-437.58;-219.63;-494.34;-223.27;-249.18;-613.41;-371.47;-457.38;-499.42;-433.01;-446.02
6;-470.20;-228.91;-503.95;-217.41;-292.13;-618.50;-381.87;-505.86;-505.63;-430.23;-440.30
7;-500.54;-245.91;-527.91;-226.86;-319.97;-599.95;-381.06;-416.05;-474.56;-431.76;-526.32

Answer

If you step through the code, line by line, it will be clear that something isn't working. In your case, the result of strsplit is a list of length 1, which holds the sliced vector. You can resolve this in a number of ways, one is to subset only the first element, or perhaps use unlist(title).

title <- "almourol_gfdl-esm2m_rcp8p5_daily_ref.csv"
title <- strsplit(title, "_")[[1]]
title <- noquote(title)
title <- paste(title[1],title[4], "discharge",title[5], "period")
title

[1] "almourol daily discharge ref.csv period"