Mauro
Mauro

Reputation: 479

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.

Upvotes: 1

Views: 483

Answers (2)

Wimpel
Wimpel

Reputation: 27792

Here is a ggplot2 approach. I myself find the code to be more readible, an so: easier to maintain.

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

library(ggplot2)
ggplot(dist, aes( x = dist[,1] ) ) + 
  geom_histogram( bins = 100, color = "black", fill = "orange" ) +
  scale_x_continuous( labels = function(x){x / 100000} ) + 
  labs( title = "VaR distribution",
        x = "P&L",
        y = "Frequency" )

enter image description here

Upvotes: 1

Lennyy
Lennyy

Reputation: 6132

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?)

Upvotes: 1

Related Questions