R 在ggplot2直方图上自动对x轴进行精确排序

R 在ggplot2直方图上自动对x轴进行精确排序,r,ggplot2,histogram,facet-grid,R,Ggplot2,Histogram,Facet Grid,我有这样一个数据集(但有数百个样本): 但正如你所看到的,酒吧并不是很有序,比较不同的样品并不容易 所以我在手边重新组织它,使它更“漂亮”(在某些方面) data$sample没有明确的最佳方法。您必须做的第一件事是定义样本之间的某种差异性度量。一个减去相关性似乎是(许多)可能的候选者之一。 然后,您可以了解如何根据相似性度量对结果进行排序。分层聚类为您提供了一个可能的顺序 在下面的代码中,我使用的示例数据是有序的和完整的。否则你可能不得不调整 # unique samples samples

我有这样一个数据集(但有数百个样本):

但正如你所看到的,酒吧并不是很有序,比较不同的样品并不容易

所以我在手边重新组织它,使它更“漂亮”(在某些方面)


data$sample没有明确的最佳方法。您必须做的第一件事是定义样本之间的某种差异性度量。一个减去相关性似乎是(许多)可能的候选者之一。
然后,您可以了解如何根据相似性度量对结果进行排序。分层聚类为您提供了一个可能的顺序

在下面的代码中,我使用的示例数据是有序的和完整的。否则你可能不得不调整

# unique samples
samples <- unique(data$sample)
## dissimilarity measure
dm <- matrix(mapply(function(x, y) 1-cor(data[data$sample == x, ]$count, data[data$sample == y, ]$count), 
                    rep(samples, times = length(samples)),
                    rep(samples, each = length(samples))), nrow = length(samples))
# single linkage clustering
hc <- hclust(as.dist(dm), method = "single")
# reorder
data$sample <- factor(data$sample, levels = samples[hc$order])
# plot
ggplot(data = data, aes(x = sample)) +
  geom_bar(aes(y = count, fill = class), color = "black", 
           position = "fill", stat = "identity")
#独特的示例

样本没有明确的最佳方法来做到这一点。您必须做的第一件事是定义样本之间的某种差异性度量。一个减去相关性似乎是(许多)可能的候选者之一。 然后,您可以了解如何根据相似性度量对结果进行排序。分层聚类为您提供了一个可能的顺序

在下面的代码中,我使用的示例数据是有序的和完整的。否则你可能不得不调整

# unique samples
samples <- unique(data$sample)
## dissimilarity measure
dm <- matrix(mapply(function(x, y) 1-cor(data[data$sample == x, ]$count, data[data$sample == y, ]$count), 
                    rep(samples, times = length(samples)),
                    rep(samples, each = length(samples))), nrow = length(samples))
# single linkage clustering
hc <- hclust(as.dist(dm), method = "single")
# reorder
data$sample <- factor(data$sample, levels = samples[hc$order])
# plot
ggplot(data = data, aes(x = sample)) +
  geom_bar(aes(y = count, fill = class), color = "black", 
           position = "fill", stat = "identity")
#独特的示例

示例它适用于我的更大数据集,我了解您的方法,因此非常完美:)它适用于我的更大数据集,我了解您的方法,因此非常完美:)
data$sample <- factor(data$sample, levels = c("C001", "C014", "C009", "C018",
                      "C012", "C004", "C016", "C002", "C015", "C011", "C003", "C007"))

ggplot(data = data, aes(x = sample)) +
  geom_bar(aes(y = count, fill = class), color = "black", 
           position = "fill", stat = "identity")
# unique samples
samples <- unique(data$sample)
## dissimilarity measure
dm <- matrix(mapply(function(x, y) 1-cor(data[data$sample == x, ]$count, data[data$sample == y, ]$count), 
                    rep(samples, times = length(samples)),
                    rep(samples, each = length(samples))), nrow = length(samples))
# single linkage clustering
hc <- hclust(as.dist(dm), method = "single")
# reorder
data$sample <- factor(data$sample, levels = samples[hc$order])
# plot
ggplot(data = data, aes(x = sample)) +
  geom_bar(aes(y = count, fill = class), color = "black", 
           position = "fill", stat = "identity")