我有以下数据集。
structure(list(Rf = c(60.105, 62.205, 64.305, 64.305, 66.405,
66.405), Es = c(0, -0.07, -0.36, -0.47, -0.39, -1.54), H = c(32.3,
-6.9, -5.59, -14.4, -6.5, -21), S = c(267, 136, 151, 114, 143,
90.4), G = c(-46.8, -47.3, -50.7, -48.5, -49, -47.8)), .Names = c("Rf",
"Es", "H", "S", "G"), class = "data.frame", row.names = c("Me",
"Et", "Pr", "iPr", "Bu", "tBu"))
我需要绘制 Rf vs H、S 和 G,对于 Es 列也是如此。总共有六个地块。
要绘制单个图,我使用以下函数:
ggplot(data=df, aes(x=Rf, y=H, label=row.names(df))) +
geom_point(size=4) +
geom_text(vjust=2) +
ylab(expression(list(Delta*H^o,~kJ/mol))) +
xlab("Molecular refraction") +
ylim((min(df$H) - 0.2*(abs(min(df$H)))), max(df$H)) +
opts(axis.line = theme_segment(size=1),
axis.text.x = theme_text(colour="black", size=15),
axis.text.y = theme_text(colour="black", size=15),
axis.title.x = theme_text(colour="black", size=15),
axis.title.y = theme_text(colour="black", size=15, angle=90),
panel.background=theme_rect(colour="white"),
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank())
我想创建一个像
f1 <- function(x.label, y.label, df, xtitle, filename) {
g <- ggplot(data=df, aes(x=x.label, y=y.label, label=row.names(df))) +
geom_point(size=4) +
geom_text(vjust=2) +
ylab(expression(list(Delta*y.label^o,~kJ/mol))) +
xlab(xtitle) +
ylim((min(df[,y.label]) - 0.2*(abs(min(df[,y.label])))), max(df[,y.label])) +
opts(axis.line = theme_segment(size=1),
axis.text.x = theme_text(colour="black", size=15),
axis.text.y = theme_text(colour="black", size=15),
axis.title.x = theme_text(colour="black", size=15),
axis.title.y = theme_text(colour="black", size=15, angle=90),
panel.background=theme_rect(colour="white"),
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank())
ggsave(filename, g)
}
像上面的例子一样调用它
f1(Rf, H, df, "Molecular refraction", "D:/temp/1.jpg")
困难在于如何转移和正确处理x.label
and y.label
,因为它们用于,和调用的aes
选项中。当前函数返回错误ggplot
ylab(expression())
ylim
Error in eval(expr, envir, enclos) : object 'x.label' not found
回答:
以下功能正常工作。aes_string
应该使用 insted of aes
inggplot
选项,而substitute
不是expression
in ylab
。
f1 <- function(x.label, y.label, df, x.title, filename) {
g <- ggplot(data=df, aes_string(x=x.label, y=y.label)) +
geom_point(size=4) +
geom_text(aes(label=row.names(df)), vjust=2) +
ylab(substitute(list(Delta*y.label^o,~kJ/mol), list(y.label=y.label))) +
xlab(x.title) +
ylim((min(df[,y.label]) - 0.2*(abs(min(df[,y.label])))), max(df[,y.label])) +
opts(axis.line = theme_segment(size=1),
axis.text.x = theme_text(colour="black", size=15),
axis.text.y = theme_text(colour="black", size=15),
axis.title.x = theme_text(colour="black", size=15),
axis.title.y = theme_text(colour="black", size=15, angle=90),
panel.background = theme_rect(colour="white"),
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank())
ggsave(filename=filename, plot=g)
}