1

我正在使用来自 ggplot2 的 ggpairs。

我需要得到 ggpairs 的对角线直方图,但想使用数据的均值和 sd 叠加正态密度曲线。

我阅读了帮助(https://www.rdocumentation.org/packages/GGally/versions/1.4.0/topics/ggpairs),但找不到执行此操作的选项。我想我必须构建自己的函数(myfunct)然后

ggpairs(sample.dat, diag=list(continuous = myfunct))

有没有人试过这个?


我尝试了以下方法:

head(data) 
      x1    x2    x3    x4    x5    x6     F1    F2 
1 -0.749 -1.57 0.408 0.961 0.777 0.171 -0.143 0.345 

myhist = function(data){ 
          ggplot(data, aes(x)) + 
             geom_histogram(aes(y = ..density..),colour = "black") + 
             stat_function(fun = dnorm, args = list(mean = mean(x), sd = sd(x))) 
           } 

ggpairs(sample.data, diag=list(continuous = myhist))

结果是:

(函数(数据)中的错误:未使用的参数(映射=列表(~x1))

4

1 回答 1

1

这个问题提供了一个将正态曲线添加到直方图中的代码示例ggplot2。您可以使用它来编写自己的函数以传递diagggpairs. 要计算数据的meansd,您可以使用例如 来获取相关数据eval_data_col(data, mapping$x)。下面的示例(可能比需要的复杂一点,但它允许您使用该wrap功能传递参数以更改颜色等。

library(GGally)    

diag_fun <- function(data, mapping, hist=list(), ...){

    X = eval_data_col(data, mapping$x)
    mn = mean(X)
    s = sd(X)

    ggplot(data, mapping) + 
      do.call(function(...) geom_histogram(aes(y =..density..), ...), hist) +
      stat_function(fun = dnorm, args = list(mean = mn, sd = s), ...)
  }

ggpairs(iris[1:100, 1:4], 
        diag=list(continuous=wrap(diag_fun, hist=list(fill="red", colour="blue"), 
                                  colour="green", lwd=2)))
于 2019-10-10T13:59:29.093 回答