2012-03-02 8 views
1

私のプロットの軸のタイトルは、テキストの中にいくつかのデータの計算を実行する関数を含めることができます。例えばR ggplot2:軸のタイトルのテキストを使って関数を取得する方法は?

ここでは、一部のデータが

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? 

enter image description here

ある私は定数としてタイトルに「時間」を維持したいが、関数は、データ変更など異なる結果を返す必要があるだろう。そしてそこに括弧を入れてください。

私はpaste()とexpression()を使っていますが、運があまりありません。どんなヒントも大歓迎です。

答えて

3

pasteまたは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) 
)) 
+0

これは完璧な仕事です。あなたの素早い答えをどうもありがとう!全体の文字列の前に 'paste 'を入れることは、私が試していなかったものでした。 – Ben

関連する問題