我写了一个用于保存ggplots的函数:
fun.save <- function(my.plot, my.plot.name, width, height){
name <- deparse(substitute(my.plot.name))
name <- paste(name, ".pdf", sep="")
cairo_pdf(name, width=width, height=height)
print(my.plot)
dev.off()
}
我使用grid.arrange
从另外两个人创建了一个图:
#create data frame
state <- c("USA", "Szwajcaria", "Kanada", "Japonia", "Korea Płd.", "Meksyk")
state <- as.factor(state)
gdp <- c(35, 30, 28, 26, 15, 9)
expenditure <- c(7.75, 8, 6, 6, 3.75, 1.5)
df.gdp <- data.frame(state, gdp, expenditure)
df.gdp$state <- factor(df.gdp$state, levels=df.gdp[order(df.gdp$gdp), "state"])
#create two bar plots
plot.tmp <- ggplot(df.gdp, aes(x=1, y=state)) +
geom_text(aes(label=state)) +
ggtitle("") +
ylab(NULL) +
scale_x_continuous(expand=c(0,0),limits=c(0.94, 1.065)) +
theme(axis.title=element_blank(),
panel.grid=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
panel.background=element_blank(),
axis.text.x=element_text(color=NA),
axis.ticks.x=element_line(color=NA),
plot.margin = unit(c(1,-1,1,-1), "mm"))
plot.gdp <- ggplot(data = df.gdp, aes(x = state, y = gdp)) +
xlab(NULL) +
geom_bar(stat = "identity") +
ggtitle("PKB na osobę (w tys. $)") +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()) +
scale_y_reverse() +
coord_flip()
plot.exp <- ggplot(data = df.gdp, aes(x = state, y = expenditure)) +
xlab(NULL) +
geom_bar(stat = "identity") +
ggtitle("Roczny wydatek na studenta (w tys. $)") +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank() ) +
coord_flip()
#merge plots
plot.gdp <- ggplot_gtable(ggplot_build(plot.gdp))
plot.exp <- ggplot_gtable(ggplot_build(plot.exp))
plot.tmp<- ggplot_gtable(ggplot_build(plot.tmp))
我可以这样保存:
pdf("GnpexpBad.pdf", width=10, height=5)
grid.arrange(plot.gdp, plot.tmp, plot.exp, ncol=3, widths=c(0.35, 0.078, 0.35))
dev.off()
但我想用我的功能去做。我打电话给我的功能:
myplot <- grid.arrange(plot.gdp, plot.tmp, plot.exp, ncol=3, widths=c(0.35, 0.078, 0.35))
fan.save(myplot, nameofmyplot, 10,5)
不幸的是它不起作用。知道如何重新排列函数以使其适用于grid
图吗?