十字架的箱形图不是唯一的

时间:2016-05-04 22:31:50

标签: r plot ggplot2

我正在尝试创建一个包含10个箱形图的图,每个图表示数据集的十分位数。但是,一些十分位数是相同的,ggplot不会绘制图形,除非它们是。我已经看到类似问题的答案建议删除非唯一十分位或添加数据以使它们唯一。然而,就我而言,重要的是要表明一些不是唯一的。

这是我的代码(没有格式化):

mydata$metric_deciles <- with(mydata, cut(metric, breaks=quantile(metric, probs=seq(0,1, by=0.1), na.rm=TRUE), include.lowest=TRUE, dig.lab = 10))
p1 <- ggplot(na.omit(mydata), aes(factor(metric), metric2))
p1 <- p1 + geom_boxplot()
p1 <- p1 + scale_x_discrete(NULL, labels = c("10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"))

其中,在十进制是唯一的数据集中,如下所示:

enter image description here

在第一行,我得到error in cut.default: 'breaks' are not unique

我正在寻找一种方法来绘制所有10个十分位数,即使有些不是唯一的(即一些箱形图将是相同的)。

1 个答案:

答案 0 :(得分:0)

错误正在发生,因为至少有一个metric的值重复并且跨越了一个分位数断点。这是cut中导致错误的原因。您可以通过按要为其创建十分位数的变量进行排名来创建十分位数。以下是内置iris数据框的示例:

# Create decile labels based on Petal.Width.
# First, rank by Petal.Width, then divide by the number of values we want in each decile.
#  Then, multiply by 10 and paste on "%" to get the label names.
iris$decile = paste0((rank(iris$Petal.Width, ties.method="random") %/% (nrow(iris)/9.99) + 1)*10, "%")

# Put the labels in the correct order
iris$decile = factor(iris$decile, levels=paste0(seq(10,100,10),"%"))

请注意,在上面的代码中,具有相同Petal.Width的某些行以不同的十进制结束,这导致cut使用quantile选择的级别时出现重复级别的问题。上面的代码使用rank并随机断开关系。

# Plot boxplots of Sepal.Width by decile of Petal.Width
ggplot(iris, aes(decile, Sepal.Width)) +
  geom_boxplot()