0

I want to overlay two histograms in a base R plot in RMarkdown.

If I run the following code (in an RMarkdown code snippet), this works fine and displays the plot below.

Code

a = rnorm(100, 1)
b = rnorm(100, 3)
h1 = hist(a, plot = F)
h1$density = h1$counts/sum(h1$counts)
h2 = hist(b, plot = F)
h2$density = h2$counts/sum(h2$counts)

{
  plot(h1
     , freq=F
     , col=alpha('green', 0.5)
     , xlim=c(-3, 7)
     , ylim=c(0,0.35)
     , ylab='Proportion'
     , xlab=""
     , main=""
     )
  plot(h2
     , freq=F
     , col=alpha('blue', 0.5)
     , xlim=c(-3, 7)
     , ylim=c(0,0.35)
     , ylab='Proportion'
     , add=T)
}

Plot

Resulting plot

Problem

The problem is that if I knit this to a pdf, I get the error could not find function "alpha". How can I get the transparency of the plots for the pdf export? A base R solution would be ideal.

ben_aaron
  • 1,504
  • 2
  • 19
  • 39
  • 3
    The `alpha` function is in the `scales` package - you must have loaded it in your interactive session (sometimes it is loaded by other packages) but not in your Rmarkdown document. Either include `library(scales)` in your markdown doc, or specify `scales::alpha()` when you call the function. – Gregor Thomas Nov 10 '21 at 15:21
  • 1
    Thanks. So obvious but I really didn't know. Thanks a lot! – ben_aaron Nov 10 '21 at 15:24

0 Answers0