0

I have this code that generates a graph of a function f and superimposes it with a histogram, but the columns of the histogram are too high. I don't know if there's a problem with the data or the function, but still I would like to make the histogram and function similar "sizes".

library(ggplot2)
dev.new()
set.seed(1684)
x = seq(15, 33, by = 0.9)
f <- function(x) {
  out <- ifelse(
    x < 15 | 33 < x,
    0,
    ifelse(
      15 <= x & x <= 24,
      (2*(x-15))/((33-15)*(24-15)),
      ifelse(
        24 < x & x <= 33,
        (2*(33-x))/((33-15)*(33-24)),
        NA_real_
      )))
  if (any((is.na(out) | is.nan(out)) & (!is.na(x) & !is.nan(x)))) {
    warning("f(x) undefined for some input values")
  }
  out
}

x_accept <- numeric(0)
while (length(x_accept) < 105) {
  x1 = runif(1, min = 15, max = 33)
  num = runif(1, min = 0, max = 1)
  if (num < (f(x1)/2/(33-15))) {
    x_accept = c(x_accept, x1)
  }
}

histo <- data.frame(x = x_accept)
dat <- data.frame(x = x, y = f(x), z = x_accept)
ggplot(dat) +
  geom_line(aes(x, y), color = "red") +
  geom_histogram(aes(z), alpha = .5, binwidth = 0.5)

enter image description here

user438383
  • 5,716
  • 8
  • 28
  • 43

1 Answers1

0

What about using builtin ggplot2 functions to create the line?

ggplot(dat, aes(x = z)) +
  geom_histogram(alpha = .5, binwidth = 0.5) + 
  # Add a line aligning to each bin.
  stat_bin(aes(y = ..count..), geom = 'line', col = 'red', binwidth = 0.5)
Oliver
  • 8,169
  • 3
  • 15
  • 37
  • It gives me this error: Error in `f()`: ! stat_bin() requires an x or y aesthetic. Run `rlang::last_error()` to see where the error occurred. –  Dec 07 '22 at 14:03
  • Sounds like you did not include `aes` in `stat_bin` – Oliver Dec 07 '22 at 14:04
  • I'm sorry I'm new to R so this is a bit confusing, but the code you sent already has the `aes` in the `stat_bin`, right? I tried also putting `aes=y` but the graph is really weird again. https://gyazo.com/bc88fb4fbc898eccbc340aaf6c19fb35 –  Dec 07 '22 at 14:14
  • No worries. Move aes(z) into `ggplot(dat, aes(x = z))`. (Updated answer to align) – Oliver Dec 07 '22 at 14:18
  • And fixed binwidth. – Oliver Dec 07 '22 at 14:19
  • Ok it gives me this https://gyazo.com/8654c5e3025facc277797c78ad8a976a but this is not really what I wanted. The function, when graphed alone will give me something like this https://gyazo.com/bc717e755956b37ee48dc16b7accc547 I basically want this graph, but behind it the histogram, I dont know if that's possible. My inicial problem is that the function values where too small compared to the histogram values –  Dec 07 '22 at 14:27
  • Perhaps: https://stackoverflow.com/a/54700242/10782538 – Oliver Dec 07 '22 at 14:28
  • Ohhhhh thank you so much, that's exactly it!! –  Dec 07 '22 at 14:33