将密度曲线拟合到 R 中的成对图中的直方图

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

我希望能够将密度曲线拟合到我添加到 R 中的成对图中的直方图。我能够使用我使用讲师的代码创建的函数添加直方图(见下文) ).

我尝试在创建直方图的代码下方的代码行 lines(density(x)) 中添加,但 R 只是忽略它,我得到的只是没有拟合密度曲线的直方图。

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)

使用 R 附带的 iris 数据集并简化面板功能,这似乎可行:

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)

您没有提供 panel.corpanel.smooth 功能。