首页 > 解决方案 > 使用 GGPLOT2 的密度图问题

问题描述

我想为 2 组绘制密度图,下面是我的代码。图书馆(ggplot2)

#Sample data
dat <- data.frame(Score = c(myfiles2Best$V2, myfilesL2Best$V2)
                  , Group = rep(c("T", "L")))
ggplot(dat, aes(x = Score)) +
        geom_density(aes(color = Group)) + xlim(0,16)

下面是输出的图像。 在此处输入图像描述

当我通过更改列的位置来更改数据框时,如下所示,这就是我的绘图的样子。

dat <- data.frame(Score = c(myfilesL2Best$V2, myfiles2Best$V2)
                  , Group = rep(c("L", "T")))

在此处输入图像描述

就个人而言,这就是他们的样子。

dat <- data.frame(Score = c(myfiles2Best$V2)
                  , Group = rep(c("T"))
ggplot(dat, aes(x = Score)) +
        geom_density(aes(color = Group)) + xlim(0,16)

在此处输入图像描述

dat <- data.frame(Score = c(myfilesL2Best$V2)
                  , Group = rep(c("L"))
ggplot(dat, aes(x = Score)) +
        geom_density(aes(color = Group)) + xlim(0,16)

在此处输入图像描述

这是完全错误的,我的设置有什么问题

rownumber  score group
1   8   T
2   8   L
3   7   T
4   7   L
5   9   T
6   8   L
7   8   T
8   7   L
9   8   T
10  8   L
11  8   T
12  9   L
13  8   T
14  8   L
15  8   T
16  8   L
17  9   T
18  7   L
19  9   T
20  7   L
21  8   T
22  10  L
23  8   T
24  8   L
25  9   T
26  8   L
27  8   T
28  8   L
29  9   T
30  8   L
31  7   T
32  10  L
33  8   T
34  10  L
35  8   T
36  7   L
37  8   T
38  7   L
39  11  T
40  9   L
41  8   T
42  9   L
43  8   T
44  10  L
45  8   T
46  9   L
47  8   T
48  8   L
49  8   T
50  7   L
51  9   T
52  8   L
53  8   T
54  9   L
55  8   T
56  7   L
57  7   T
58  9   L
59  10  T
60  8   L

标签: rggplot2

解决方案


ggplot2::geom_density使用基本 Rdensity函数来计算密度。(请参阅?geom_density。)这需要一个平滑参数,默认情况下使用名为“nrd0”的规则,该规则是出于“历史和兼容性原因”而选择的。(请参阅?density。)根据此参数,您将获得具有不同外观的密度图。

来自?bandwidth

bw.nrd0 实现了一个经验法则,用于选择高斯核密度估计器的带宽。它默认为标准偏差最小值的 0.9 倍和四分位距除以样本大小的 1.34 倍负五分之一幂(= Silverman 的“经验法则”,Silverman (1986, page 48, eqn (3.31)) ) 除非四分位数重合,否则肯定会得到肯定的结果。

在您的示例中,这两个子组看起来具有不同的标准差和 IQR,因此对我来说,根据是否为它们共同计算平滑参数(如组合图的情况)或分别。

如果您希望密度图在分组和单个基础之间对应,请手动指定带宽:

ggplot(df, aes(x = score)) +
  geom_density(aes(color = group), bw = 0.3) + 
  xlim(0,16)

ggplot(subset(df, group == "L"), aes(x = score)) +
  geom_density(aes(color = group), bw = 0.3) + 
  xlim(0,16)

ggplot(subset(df, group == "T"), aes(x = score)) +
  geom_density(aes(color = group), bw = 0.3) + 
  xlim(0,16)

推荐阅读