1

我希望我的绘图轴标题在文本中包含一个对某些数据执行计算的函数。

例如这里有一些数据

a<-data.frame(time="1000",x=rnorm(10,12,3))
b<-data.frame(time="2000",x=rnorm(50,13,4))
c<-data.frame(time="3500",x=rnorm(50,12,4))
d<-data.frame(time="5000",x=rnorm(7,14,5))
e<-data.frame(time="7000",x=rnorm(20,10,3))
f<-data.frame(time="7500",x=rnorm(15,11,3))
g<-data.frame(time="9000",x=rnorm(15,10,5))
h<-data.frame(time="9500",x=rnorm(35,30,2))
i<-data.frame(time="10000",x=rnorm(30,28,4))
a2i<-rbind(a,b,c,d,e,f,g,h,i) 

library(ggplot2)
a2i$time<-as.numeric(levels(a2i$time))[a2i$time] 
ggplot(a2i,aes(time,x))+stat_smooth()+geom_point()+
# now let's try to put on a label with a function
# mixed in with the text
#
xlab("Time (total number of observations = paste(length(a2i$x))))")
#
# but that's no good, the function is not executed, just printed
# How can I get a function to work in the axis title?

在此处输入图像描述

我想将标题中的“时间”保持为常数,但让函数随着数据的变化返回不同的结果。并把括号也放在那里。

我尝试过 paste() 和 expression(),但运气不佳。任何提示将非常感谢。

4

1 回答 1

3

您应该首先使用pasteor构建一个包含所需测试的字符串,sprintf然后将其提供给xlab. 特别是paste不应该在字符串里面。

xlab( paste( 
  "Time (total number of observations = ", 
  length(a2i$x), 
  ")", 
  sep="" 
) )

# Equivalently
xlab( sprintf( 
  "Time (total number of observations = %s)", 
  length(a2i$x) 
) )
于 2012-03-02T07:34:06.750 回答