【问题标题】:R - Plot Function with Variable as X-axis NameR - 以变量为 X 轴名称的绘图函数
【发布时间】:2015-03-21 16:04:03
【问题描述】:

我有一个简单的函数,它将创建传递变量的直方图,但我希望该函数将直方图命名为“X 的直方图”,其中 X 是变量的名称。

我还希望它也将 X 轴命名为变量的名称。

我该怎么做?

这是目前的功能,但没有给出我想要的正确标签:

plot.histogram <- function (x){
  hist(x, main = "Histogram of x", xlab = "x")
}

谢谢

【问题讨论】:

  • 在您指定 main = "Histogram of x"xlab = "x" 的那一刻,这意味着直方图将始终使用这些确切的短语进行标记。您是否知道仅hist(x) 似乎可以提供您要求的输出?
  • 是的,我知道它会给我那个输出。我真正想要的是如何用传递的变量的名称在函数中标记事物。并不是我一定要使用这个函数,我只是想学习如何根据函数中传递的变量的名称来分配事物的标签。
  • 谢谢 ping,这正是我想要的。

标签: r dataframe histogram


【解决方案1】:

当您需要调整文本时。找到这个 SO 帖子:Name of Variable in R

sweet = rnorm(100)

plot.histogram <- function (x){

    hist(x, main = paste("Awesome Histogram of",substitute(x)), xlab = paste(substitute(x)))
}

plot.histogram(sweet)

更新为使用 data.table

x = data.table( 'first'=rnorm(100),'second'=rnorm(100),'third'=rnorm(100))
plot.histogram <- function (x){
    if( is.null(names(x) ) ){
        mname = substitute(x)  
        hist(x, main = paste("Histogram of", mname ), xlab = paste( mname ))
    }else{
        mname = names(x)
        hist(x[[mname]], main = paste("Histogram of", mname ), xlab = paste( mname ))
    }
}
x[ , plot.histogram(.SD), .SDcols=c(1) ]

【讨论】:

  • 快速跟进,如果我尝试将此函数用作 apply() 语句的一部分,它不会保留名称。有什么建议吗?应用(df,2,plot.histogram)。它重命名每个 newX[,1] 而不是放置正确的标签
  • @nate-thompson 您是否希望将 plot.histogram 函数应用于 data.frame 的所有列? hist 函数不适用于非数字列
  • 正确,这就是我想要做的。我的整个数据集都有数字列,它给了我每列的直方图输出,但每个图的标题和标签完全相同“newX[,1] 的直方图
  • 很抱歉真的对此回复迟了。而不是使用 apply 函数,只需使用一个简单的 for 循环。 for(i in 1:length(x)){ x[ , plot.histogram(.SD), .SDcols=c(i) ] }
猜你喜欢
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多