seed=1234
df=data.frame(rnorm(50)*100)
names(df)="Temperature"; df
nn = length(df$Temperature)
title = "Daily Temperature"
title2 = substitute(paste(title,"(",degree,"C)"))
title3 = paste(title,"\n(n = ",nn,")")
h1 = ggplot(df, aes(x=df[,1]))+ geom_density(colour = "black", fill = "white", binwidth = 5)
+ labs(list(title = title3, x = title2, y = "Counts"))
h1
上面的迷你示例描述了我在x轴上显示“title2”的问题。我已经搜索并尝试了许多好的建议(例如,aes_string,expression等等),但仍然无法使其工作。如果我用title2替换title2; title2 = expression(paste("Daily Temperature (",degree,"C)"))
,它运作正常。在此先感谢您的帮助!文斯
答案 0 :(得分:2)
require(ggplot2) # not everyone has this package loaded by default
seed=1234
df=data.frame(rnorm(50)*100)
names(df)="Temperature"; df
nn = length(df$Temperature)
title = "Daily Temperature"
要干净利落地完成这项工作需要积累经验。参见?plotmath和?substitute。我发现如果您使用paste
和*
,通常不需要使用plotmath ~
。
# first argument to substitute is an expression object
# you need to supply a list as the second argument to substitute
title2 = substitute(title*"("*degree*C*")", list(title=title) )
title3 = paste(title,"\n(n = ",nn,")")
h1 = ggplot(df, aes(x=df[,1]))+
geom_density(colour = "black", fill = "white", binwidth = 5) +
labs(list(title = title3, x = title2, y = "Counts"))
h1
在plotmath表达式中使用括号的另一种方法是使用plotmath list
函数(这与普通列表函数的不同之处在于它创建了逗号分隔的表达式。)只有一个表达式,它只是给出了括号:
title2 = substitute(title*list(degree*C), list(title=title) )