Dean Wilkinson
Dean Wilkinson

Reputation: 33

Fitting Density Curves to Histograms put into a Pairs Plot in R

I am want to be able to fit a density curve to histograms that I have added to a pairs plot in R. I am able to add the histograms using a function that I created using code from an instructor (see below).

I have tried adding in the code line lines(density(x)) underneath the code that creates the histograms but R just ignores it and all I get are histograms without density curves fitted to them.

panel.hist = function(x, ...) {
  usr = par("usr"); on.exit(par(usr))
  par(usr = c(usr[1:2], 0, 1.5))
  h = hist(x, plot = FALSE, freq = FALSE) 
  breaks = h$breaks; nB = length(breaks)
  y = h$counts; y = y/max(y)
  rect(breaks[-nB], 0, breaks[-1], y, col = "cyan", ...)
  lines(density(x))
}
pairs(squid[, c("DML", "weight", "eviscerate.weight", "ovary.weight", "nid.length", "nid.weight")], upper.panel = panel.smooth, diag.panel = panel.hist, lower.panel = panel.cor)

Upvotes: 0

Views: 441

Answers (1)

dcarlson
dcarlson

Reputation: 11076

Using the iris data set that comes with R and simplifying your panel function, this seems to work:

data(iris)
panel.hist = function(x, ...) {
  usr = par("usr"); on.exit(par(usr))
  par(usr = c(usr[1:2], 0, 1.5))
  hist(x, freq = FALSE, col="cyan", add=TRUE) 
  lines(density(x))
}
pairs(iris[, 1:4], upper.panel = panel.smooth, diag.panel = panel.hist)

You did not provide panel.cor or panel.smooth functions.

Pairs Plot

Upvotes: 1

Related Questions