如何使用ggplot2将具有连续数字的条形图堆叠为离散数字

How to stack bar graph with continuos numbers as a discrete numbers using ggplot2

我正在尝试用图表表示生产过程的质量。

对于这个问题,假设 data.frame 被描述为:

df2 <- data.frame(size = c("XS", "S", "M", "L", "XL"),
                    ok = c(1, 3, 4, 2, 1),
                 notok = c(0, 1, 1, 2, 0))      

size ok notok
 XS  1     0
  S  3     1
  M  4     1
  L  2     2
 XL  1     0

现在我想展示一下,我生产的很多产品都还不错。所以我尝试:

ggplot(df2, aes(x=size, y=(ok+notok), fill=ok)) +
    geom_bar(stat="identity")

然而,我得到的结果是一个显示 ok 变量的图表,就好像 "ok" 是一个比例尺。

我也尝试过使用 fill=factor(ok) 但结果不是我所期望的。

我怎样才能得到一个图表来显示每个箱子中有多少是好的?

像这样

如果数据是长格式而不是宽格式,

ggplot 往往效果最好。要在两者之间进行转换,您可以使用优秀的 reshape 包。试试这个:

require(reshape)
df3 <- melt(df2, id.vars = "size")

您的数据现在为长格式,如下所示,可以更轻松地绘制:

   size variable value
1    XS       ok     1
2     S       ok     3
3     M       ok     4
4     L       ok     2
5    XL       ok     1
6    XS    notok     0
7     S    notok     1
8     M    notok     1
9     L    notok     2
10   XL    notok     0


ggplot(df3, aes(x = size, y = value)) +
  geom_bar(stat = "identity", aes(fill = variable))

...生成下图: