【问题标题】:How to Make return value of function for legend如何为图例制作函数的返回值
【发布时间】:2012-03-14 22:32:20
【问题描述】:

我制作了一个绘制 csv 文件中数据的函数。

我想从调用函数时使用的变量名称中获取图例中的标签。

使用下面的代码,names(dataPlot1) 在图例中使用名称“temp1”“temp2”“temp3”。我想把它设为“x”、“y”、“z”。我该怎么做?

temperature <- function(temp1,temp2,temp3)
{
    dataPlot1 <- data.frame(temp1,temp2,temp3)
    matplot(dataPlot1,axes=T,frame=T,type="l",
            xlab="time (hour)",ylab="temperature(C)",
            main=names(dataPlot1))
    lines(dataPlot1[1],lty=1,col="blue")
    lines(dataPlot1[2],lty=2,col="red")
    lines(dataPlot1[3],lty=2,col="forestgreen")  
    legend("topright",names(dataPlot1),lty=c(1,2,2),
            col=c("blue","red","forestgreen"))

}
temperature(x,y,z)

【问题讨论】:

    标签: r function


    【解决方案1】:

    也许是这样的:

    temperature <- function(temp1,temp2,temp3)
    { t1 <- deparse(substitute(temp1))
      t2 <- deparse(substitute(temp2))
      t3 <- deparse(substitute(temp3)) 
        dataPlot1 <- data.frame(temp1,temp2,temp3)
        matplot(dataPlot1,axes=T,frame=T,type="l",
                xlab="time (hour)",ylab="temperature(C)",
                main=names(dataPlot1))
        lines(dataPlot1[1],lty=1,col="blue")
        lines(dataPlot1[2],lty=2,col="red")
        lines(dataPlot1[3],lty=2,col="forestgreen")  
        legend("topright", c(t1,t2,t3), lty=c(1,2,2),
                col=c("blue","red","forestgreen"))
    

    【讨论】:

      【解决方案2】:

      您有多种选择:

      1. 为您的数据命名:dataPlot1 &lt;- data.frame(x=temp1, y=temp2, z=temp3)
      2. 稍后分配名称:`colnames(dataPlot1)
      3. 将所需文本作为legend= 参数提供给legend() 调用。
      4. 更改您的函数并添加第四个参数,例如 legtxt=c("x","y","z") 并将其传递给 legend

      【讨论】:

      • 也许我误解了这个问题(因此编辑得不好),但我认为 OP 想要从函数本身访问传递给函数的变量的名称。即temperature(foo,bar,foobar) 将用“foo”、“bar”和“foobar”标记图例,而不会将其硬编码到函数体中。
      • 如果您传入一个 with names 的 data.frame,选项一仍然有效。名称信息必须来自某个地方...我添加了第四个选项。但是,如果数据没有附加名称,则无法在图例中自动分配名称。
      • 好的,是的。更改函数以接受包含所有三个变量的单个数据框可能比以某种方式使用get 更可取。 :)
      猜你喜欢
      • 1970-01-01
      • 2017-03-26
      • 2016-08-13
      • 2015-11-24
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多