Search code examples
rr-markdownmarkdownbookdown

Histogram in bookdown document appears two times


When I do bookdown::render_book(...) on my document which contains the following code segment

#```{r eval=TRUE, include=TRUE, echo=FALSE}  # only that you can see my chunk options (it's of course not commented out)

# My data for a histogram
Distance = rnorm(n = 1000, mean = 5, sd = 0.5)

# Creating the histogram
hist(Distance,
    freq=FALSE,
    xlim = c(0, 9),
    ylim = c(0, max(hist(Distance)$density + 0.2)),
    xlab = "Distance [mm]",
    ylab = "Density",
    main = "Histogram")
abline(v=5.5,lwd=2,lty=2,col="red")

#```

I get this Output

enter image description here

and like the code suggest the first histogram shouldn't appear - the one with the Frequency on the y-axis.

Question: What should I do to avoid the appearance of the first histogram?!

Thanks in advance!


Solution

  • The problem lies in the line ylim = c(0, max(hist(Distance)$density + 0.2)), where you call the histogram of Distance. This plots the histogram of Distance before returning the values you need as arguments for your real plot.

    If you want to use a property of a histogram as an argument, you should store the histogram in a variable before drawing your real histogram and then just refer to it.

    So, before doing anything else, use h = hist(Distance)

    Then, you may change the ylim specification to: ylim = c(0, max(h$density + 0.2)),

    There should only be one histogram, then.