基于 4 个变量的堆积条形图和 ggplot2

Stacked bar plot based in 4 variables with ggplot2

我有这样一个数据框:

nthreads ab_1 ab_2 ab_3 ab_4 ...
1        0    0    0    0    ...
2        1    0    12   1    ...
4        2    1    22   1    ...
8        10   2    103  8    ...

每个 ab_X 代表在我的代码中触发中止的不同原因。我想在显示 nthreads vs 中止的条形图中总结所有中止原因,每个条中堆叠不同 ab_X。

我可以

ggplot(data, aes(x=factor(nthreads), y=ab_1+ab_2+ab_3+ab_4)) +
  geom_bar(stat="identity")

但它只给出了中止的总数。我知道有一个填充 aes,但我不能让它与连续变量一起工作。

你必须先 melt 数据框

library(data.table)
dt_melt <- melt(data, id.vars = 'nthreads')
ggplot(dt_melt, aes(x = nthreads, y = value, fill = variable)) + 
    geom_bar(stat = 'identity')

它给出了中止的总数,因为您将它们加在一起:)

您需要先将数据从宽格式转换为长格式,为中止原因创建一列,为它们的值创建第二列。您可以为此使用 tidyr::gather。我还发现 geom_colgeom_bar:

更方便
library(tidyr)
library(ggplot2)
data %>% 
  gather(abort, value, -nthreads) %>% 
  ggplot(aes(factor(nthreads), value)) + 
    geom_col(aes(fill = abort)) + 
    labs(x = "nthreads", y = "count")

请注意,值的范围使得一些条形图很难看清,因此您可能需要考虑尺度甚至小平面。