R boxplot - 如何针对给定的上限和下限而不是最小值和最大值进行标准化

时间:2017-11-02 08:03:14

标签: r normalization boxplot

我有几个测量值,需要在相同的箱线图中显示,尽管有完全不同的比例。每组(=测量类型)都有自己特定的高和低接受限制。

数据应在R中标准化,以便下限始终为-1,并且所有组的上限始终为+1。然后我将设置Y轴,以便正确显示所有测量值。

到目前为止,我已设法绘制最小(NUM_VALUE)为-1且最大(NUM_VALUE)为+1的箱线图,但这不是我想要的最终结果。

虚假数据(只是表格的一部分):

ITEMID      NAME    SERIALID    NUM_VALUE   LOWER_LIMIT UPPER_LIMIT
Itemcode1   group1  SN1000      62.1        50          80
Itemcode1   group1  SN1001      62.6        50          80
Itemcode1   group1  SN1002      63.9        50          80
Itemcode1   group2  SN1006      1526.79     1526        1528
Itemcode1   group2  SN1007      1526.799    1526        1528
Itemcode1   group3  SN1015      1815.09     1814        1816
Itemcode1   group3  SN1016      1815.094    1814        1816
Itemcode1   group3  SN1017      1815.098    1814        1816
Itemcode1   group4  SN1025      1526.751    1526        1527
Itemcode1   group4  SN1026      1526.62     1526        1527
Itemcode1   group5  SN1028      1816.155    1816        1817
Itemcode1   group5  SN1029      1816.245    1816        1817

R代码:

library(ggplot2)
library(data.table)
df <- read.table("data3.csv", header=TRUE, sep=";", stringsAsFactors=FALSE)
skl <- function(x){(x-min(x))/(max(x)-min(x))*2-1}
df <- transform(df,scaled=ave(df$NUM_VALUE,df$NAME,FUN=skl))
ggplot(df, aes(x=df$NAME, y = df$scaled)) + geom_boxplot()
到目前为止

图表: boxplot

我对R.很新。

问题:如何按组对UPPER_LIMIT和LOWER_LIMIT缩放箱图并将其全部显示在同一图表中?

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

而不是使用min()max(), you can change your function skl()to also take更低的and上限`。

改编后的功能如下所示:

skl&lt; - function(x,lower,upper){       (x - 更低)/(上 - 下)* 2 - 1       }

您可以使用data.frame

浏览apply()的行
df$scaled <- apply(df[, 4:6], 1, function(row) {
  skl(x = row[1], lower = row[2], upper = row[3])
})

结果如下:

df$scaled
 [1] -0.19333333 -0.16000000 -0.07333333 -0.21000000 -0.20100000  0.09000000  0.09400000  0.09800000
 [9]  0.50200000  0.24000000 -0.69000000 -0.51000000

使用您的代码,boxplot将如下所示:

library(ggplot2)
ggplot(df, aes(x=df$NAME, y = df$scaled)) + geom_boxplot()

boxplot