【问题标题】:R ggplot2: How to get a function in with the text of the axis title?R ggplot2:如何使用轴标题的文本获取函数?
【发布时间】:2012-03-02 07:18:09
【问题描述】:

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

例如这里有一些数据

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(),但运气不佳。任何提示将非常感谢。

【问题讨论】:

    标签: r function ggplot2 axis-labels


    【解决方案1】:

    您应该首先构建一个包含您想要的测试的字符串, 与pastesprintf,然后将其提供给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) 
    ) )
    

    【讨论】:

    • 完美地完成了这项工作。非常感谢您的快速答复!将paste 放在整个字符串的前面是我没有尝试过的。
    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2018-03-27
    相关资源
    最近更新 更多