This is the right solution, but the original data includes a value of 1
, so OP will likely want,
br <- seq(0, 60, 5)
A more robust solution would be, to take the vector of interest, say x
, and make a wrapper function for hist,
x <- c(1, 13, 15, 17, 19,
21, 21, 23, 23, 23,
23, 25, 27, 30, 33,
33, 33, 33, 36, 36,
38, 40, 46, 48, 54)
my_hist <- function(x, ..., width = 5, anchor = 0, range_lables = FALSE) {
offset <- anchor %% width
low <- width * (min(x) - offset) %/% width + offset
high <- width * (max(x) + width - offset - 1) %/% width + offset
br <- seq(low, high, width)
hist(x, breaks=br, ..., xaxt = "n")
if (range_lables) {
labs <- paste(br[seq_along(br[-1])] + c(0, rep(1, length(br) - 2)), br[-1], sep = "-")
at <- br[seq_along(br[-1])] + width / 2
axis(1, at, labs, las = 2)
} else {
axis(side=1, at = br)
}
}
my_hist(x, main = "My awesome Histogram!", xlab = "Ages")
my_hist(x, main = "My awesome Histogram!", xlab = "Ages", width = 10)
my_hist(x, main = "My awesome Histogram!", xlab = "Ages", width = 8, anchor = 3)
my_hist(x, main = "My awesome Histogram!", xlab = "Ages", range_lables = TRUE)
Created on 2020-09-16 by the reprex package (v0.3.0)