**Edited with an example of my dataset"
I'm currently working on a loop in R to produce 21 contour plots from 21 model output spreadsheets in ggplot. The entire loop is now working and printing to a single pdf, but I would like to add direct.labels to each plot along the contours. I'm not confident in how to do this whilst making sure the loop still executes?
My data:
x y z
0.175 1.97 1113.17
0.175 1.975 1112.31
0.175 1.98 1111.44
0.175 1.985 1110.66
0.175 1.99 1109.72
0.175 1.995 1109.28
0.175 2 1107.6
0.18 0 1321.99
0.18 0.005 1321.99
0.18 0.01 1321.99
0.18 0.015 1321.99
0.18 0.02 1321.99
0.18 0.025 1321.99
0.18 0.03 1321.99
0.18 0.035 1321.99
0.18 0.04 1321.99
My code:
filenames <- list.files(path=".",
pattern="csv",
full.names=TRUE)
pdfnames <- paste(substr(filenames, 1, nchar(filenames)-4),".pdf",sep="")
pdfmaster <- paste(substr(filenames,1,15),".pdf",sep="")
# List of variables being displayed
variable = c("Dimensionless potential temperature",
"Melt fraction",
"Melting rate",
...)
#Creates a contour plot in ggplot of the variable in xz space
makeplot <- function(filename) {
xx <- which(filenames==filename)
data <- as.data.frame(read.csv(file=filename), header = FALSE)
ggplot(data=data, mapping = aes(x = data[,2],
y=data[,1],
z = data[,3])) +
geom_raster(data=data, aes(fill=data[,3]), show.legend=TRUE, interpolate
= FALSE) +
scale_fill_gradient(limits=range(data[,3]), high = 'red', low = 'white') +
geom_contour(bins = 30, colour = "black") +
xlab(label = "Distance from ridge axis") +
ylab(label = "Depth") +
theme_bw()+
coord_cartesian(
ylim = c(0,1), xlim = c(0,2))+
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
guides(fill=guide_legend(title=variable[xx]),
guide_colorbar(title=NULL))
}
# Making one pdf file per plot
for (f in 1:length(filenames)) {
pdf(file=pdfnames[f], height=3, width=6)
print(makeplot(filenames[f]))
dev.off()
}
# Making all plots in one pdf
pdf(file=pdfmaster[1], height=6, width=12)
for (f in 1:length(filenames)) {
print(makeplot(filenames[f]))
}
dev.off()