首先定义绘图函数(以便它们可以接受您将要更改的参数:
chart_high_mom <- function(fontsize, titlesize, geomtextsize, ftitle,
x = NULL, # a data frame containing the data to plot
datecol, # name of column holding yyyy-mm-dd date series
valcol, # name of column holding value to use for calculation
fstartdate, # date in yyyy-mm-dd format specifying first date to plot
fenddate # date in yyyy-mm-dd format specifying last date to plot
) {
# strip the data frame down
x <- subset(x,select = c(datecol,valcol))
colnames(x) <- c('mydate','myval')
# create year and month columns
x$year <- as.numeric(format(as.Date(x$mydate), format="%Y"))
x$month <- as.numeric(format(as.Date(x$mydate), format="%m"))
# create month-on-month change column
mydata.xts <- xts(x$myval,order.by=x$mydate)
x$myvalmom <- diff(mydata.xts,lag=1)/lag(mydata.xts,1)
plotlist <- list()
print(paste("i = ",i," and fontsize = ",fontsize," and titlesize = ",titlesize,sep=""))
thisplot <- ggplot(x[x$mydate>=fstartdate &
x$mydate<=fenddate,],
aes(x=month(mydate,label=TRUE),y=year(mydate),
fill = myvalmom, label = sprintf("%1.1f%%", 100*myvalmom))) +
scale_y_date(major="years", format="%Y") +
geom_tile() +
geom_text(data=x[x$mydate>=fstartdate &
x$mydate<=fenddate,],size = geomtextsize,
colour = "black") +
scale_fill_gradient2(low = "blue", high = "red",midpoint=0) +
scale_x_discrete(expand=c(0,0)) +
scale_y_reverse(breaks=1980:2012, labels=1980:2012, expand=c(0,0) ) +
force(opts(axis.text.y =
theme_text(size = force(fontsize), colour = "grey50"),
axis.text.x = theme_text(size = force(fontsize), colour = "grey50"),
plot.title = theme_text(size = titlesize),
title = ftitle,
panel.grid.minor = theme_blank(),
axis.ticks = theme_blank(),
panel.grid.major = theme_blank(),
axis.title.y = theme_blank(),
axis.title.x = theme_blank(),
panel.background = theme_rect(fill = "transparent",colour = NA),
legend.position = "none"
))
return(thisplot)
}
....然后打电话给他们。并使用您想要的参数值调用它们:
set.seed(12345)
mydf <- data.frame(passdate=seq(as.Date("1995/1/1"), by="month", length.out=204),passval=runif(204, min=25, max=100),ignoreval=runif(204, min=-21, max=-2))
myplots <- list()
for (i in 1:2) { # loop to create plot with two different sets of font sizes
if (i == 1) {
print(fontsize <- 8)
print(titlesize <- 32)
print(geomtextsize <- 4)
print(ftitle <- "medium");
myplots[[1]] <-chart_high_mom(fontsize= fontsize , titlesize= titlesize , geomtextsize= geomtextsize , ftitle= ftitle , x=mydf, 'passdate', 'passval', '1995-02-01', '2011-12-31')
png(filename = "chart1.png", width = 700, height = 600, units = "px", res = NA)
print(myplots[[1]])
dev.off() }
if (i == 2) {
fontsize <- 24
titlesize <- 12
geomtextsize <- 5
ftitle <- "large";
myplots[[2]] <-chart_high_mom(fontsize= fontsize , titlesize= titlesize , geomtextsize= geomtextsize , ftitle= ftitle , x=mydf, 'passdate', 'passval', '1995-02-01', '2011-12-31')
png(filename = "chart2.png", width = 700, height = 600, units = "px", res = NA)
print(myplots[[2]])
dev.off() } }
# end of calling code