Search code examples
rplotaxis-labels

R: labels() command doesn't work when trying to set x axis labels onto a histogram


Simplifying and trying to make my error reproducible, my code is the following, it generates a histogram and set x axis and y axis afterwards:

    set.seed(100)

    dist <- data.frame(rnorm(200, sd = 300000))

    histogram <- hist(dist$rnorm.200., col = "orange", breaks = 100, main = "VaR distribution", xlab = "P&L", axes = FALSE)

    axis(1, at = seq(min(dist), max(dist), length = 7))
    labels(formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0))

    axis(2, at = seq(from = 0, to = max(histogram$counts), by = 5))
    labels(formatC(seq(from = 0, to = max(histogram$counts), by = 5), format = "d"))

The command to set labels on axis y works, but the x axis labels command doesn't, which is the following:

axis(1, at = seq(min(dist), max(dist), length = 7))
    labels(formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0))

instead of getting a sequence of 7 values of dist$norm.200. divided by 1000000 and without decimals, I get the default values set by histogram() function.

Could anyone help me?

Edition: Neither the y axis labels command nor x works, I thank it did in my original code because it matched causally.


Solution

  • you should use labels as an argument of the axis() function, not as a separate function. Something like this:

    set.seed(100)
    
    dist <- data.frame(rnorm(200, sd = 300000))
    
    histogram <- hist(dist$rnorm.200., col = "orange", breaks = 100, main = "VaR distribution", xlab = "P&L", axes = FALSE)
    
    axis(1, at = seq(min(dist), max(dist), length = 7), labels = formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0))
    
    axis(2, at = seq(from = 0, to = max(histogram$counts), by = 5), labels = (formatC(seq(from = 0, to = max(histogram$counts), by = 5), format = "d")))
    

    Also, you should realize formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0) only returns zeroes, so perhaps you'd like to give some more attention towards what these labels actually should be. (Perhaps divide by 100000 instead?)