Equal Width Histogram

I am at a loss to create a histogram with an equal width of 5 where the data does not overlap.

Here is the dataset:
Q1DM_ASSIGNMENT2$age 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

hist(Q1DM_ASSIGNMENT2$age, breaks=15, main="Question 1",
xlab="age",
xlim=c(5,60))

Also, is there a way to show the different ages in each break?

Is this what you had in mind:

hist(Q1DM_ASSIGNMENT2$age, breaks=seq(5,60,5), main="Question 1",
     xlab="age", xlim=c(5,60))

If you want a label at every break, you can do:

br = seq(5,60,5)

hist(Q1DM_ASSIGNMENT2$age, breaks=br, main="Question 1",
     xlab="age", xlim=c(5,60), xaxt="n")

axis(side=1, at=br)

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)

Thank you so much for your assistance!

If any of the replies worked for you, please make sure to mark it as a solution.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.