neizod
neizod

Reputation: 1577

In R, can I change histogram title without specify `main=`?

Ok, suppose I create a very simple histogram with my function:

hist(my.fun(100))

The title of my histogram show Histogram of my.fun(100). This is perfectly fine for me! I like the way R automatically recognize my.fun(100) and put it in the title and label.

But then I do complex computation, says:

n <- my.complex.algo.that.compute.size(args)
hist(my.fun(n))

This time, the title show Histogram of my.fun(n). Which gives no clue on how large is n. I know that n will be evaluate to some integer, suppose that for this run n == 42, I like to see the title of histogram show Histogram of my.fun(42) instead.

Is this possible without specifying the title by myself (no main=paste(...)). I've try these and fail:

hist(my.fun(`n`))
hist(my.fun(eval(n)))

Upvotes: 1

Views: 3400

Answers (2)

neizod
neizod

Reputation: 1577

After I look up and learn from hist source code, I can say that this is impossible when hist is called as top level function. Because of this line in the source code:

xname <- paste(deparse(substitute(x), 500), collapse = "\n")

The deparse(substitute(x)) try to catch (not-yet-evaluated) expression tree and turn it into a string. This mean whatever expression I type as first argument for the hist function, it will be turned into a string right away without any evaluation.

To achieve this, I need to force evaluation at some leaf of the expression tree. Which (luckily enough that I just learn about it) can be done with substitute, and use do.call to pass the evaluated expression tree as an argument for hist function:

n <- my.complex.algo.that.compute.size(user.args)   # suppose this calc return 42
evaluated.arg <- substitute(my.fun(x), list(x=n))   # now this will be my.fun(42)
do.call(hist, list(evaluated.arg))

Upvotes: 0

Spacedman
Spacedman

Reputation: 94212

If you restrict the thing you are histogramming to a function of a single argument, n, then you can do this:

nhist = function(f,n){
   hist(f(n),
   main=paste0(
     "Histogram of ",
     deparse(substitute(f), 500),"
     (",n,")", collapse = "\n"))}

Which you call slightly differently:

Z=100
nhist(runif, Z)

You have to pass f and n separately since there's no way hist can figure out what was passed to f.

Upvotes: 3

Related Questions