**以我的数据集示例进行编辑”
我目前正在R中的一个循环上,从ggplot中的21个模型输出电子表格中生成21个轮廓图。整个循环现在可以正常工作并打印为单个pdf,但是我想在轮廓上向每个图添加direct.label。在确保循环仍然执行的同时,我不确定如何执行此操作?
我的数据:
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
我的代码:
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()