【问题标题】:Fitting Density Curves to Histograms put into a Pairs Plot in R将密度曲线拟合到直方图,放入 R 中的配对图中
【发布时间】:2021-10-04 16:31:35
【问题描述】:

我希望能够将密度曲线拟合到已添加到 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 histogram


    【解决方案1】:

    使用 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 函数。

    【讨论】:

    • 抱歉忘了说我有一个函数可以添加变量的相关性,但它工作正常。此代码也有效,非常感谢!
    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多