Search code examples
rplotlattice

Add curve to Lattice barchart


I hope the question is correctly posted. It is probably trivial but I am still not able to answer. I checked several options, included the info contained here, but with no fortune. Perhaps, I am still not used to Lattice commands, or the problem is actually not relevant.

I would overlap a barchart with a curve, such as (let's say) a normal standard distribution curve or the density distribution of the data.

Please consider the following data as example, representing the results of several die rolls:

e11 <- data.frame(freq = rep(seq(1, 6, 1), c(53, 46, 42, 65, 47, 44)))

plot_e11 <- barchart(e11,
            horizontal = FALSE,
            type = "density",
            main = "Die results frequencies",
            panel = function(x, ...){
                    panel.barchart(x, ...)
                    panel.abline(densityplot(e11$freq))})
print(plot_e11a)

It returns the normal barchart instead of the expected result.

normal barchart

How can I add a curve to the barchart, such as the one in the following example?

plot_e11b <- densityplot(e11$freq,
                     plot.points = FALSE)

density plot


Solution

  • panel.abline is the wrong panel function.

    panel.abline adds a line of the form y = a + b * x, or vertical and/or horizontal lines.

    densityplot(e11$freq, 
                panel=function(x, ...) { 
                  tab <- table(x)
                  panel.barchart(names(tab), tab/length(x),
                                 horizontal=FALSE)              
                  panel.densityplot(x, plot.points=FALSE)},
                ylim=c(0, 0.3))
    

    lattice plot