ggplot - 使用数值填充堆积的条形图

时间:2014-09-27 20:55:35

标签: r ggplot2

我想构建一个堆积条形图,在字段fill中提供数值而不是类别。

这是我到目前为止的图表:

graph

在堆积条形图的ggplot example中,字段fill对应cut数据集的diamonds列。 此列对应于:

> class(diamonds$cut)
[1] "ordered" "factor"
因此,我认为不同术语的频率

> head(diamonds$cut)
[1] Ideal     Premium   Good      Premium   Good      Very Good
Levels: Fair < Good < Very Good < Premium < Ideal
计算

并用于填充条形图。

ggplot stacked bar chart

在我的情况下,我在X(我的数据框中tot)上显示的条形图的每个值都由两种类型的值形成:updown。这些对应于我的数据框中的列:

> head(cyt.4)
                                                             COG tot up down
1                           [C] Energy production and conversion  17 16    1
2 [D] Cell cycle control, cell division, chromosome partitioning   0  0    0
3                        [E] Amino acid transport and metabolism  34 30    4
4                        [F] Nucleotide transport and metabolism  11  9    2
5                      [G] Carbohydrate transport and metabolism  13  9    4
6                          [H] Coenzyme transport and metabolism   3  3    0

例如,X(tot)值为10的条形可以划分为up = 7,down = 3。现在,让我们说我将红色分配给up并将绿色分配给down,我希望我的酒吧可以填充70%(7分(满分10分)红色和30分钟%绿色(10个中的3个)。

我几天都在苦苦挣扎,但没有得到任何有效的结果。

1 个答案:

答案 0 :(得分:3)

转换您的数据&#34; wide&#34;到&#34;长&#34;格式,例如使用reshape包。然后ggplot中的事情变得更容易了。重组后的数据框包含variable,其值为&#34; down&#34;和&#34; up&#34;。这可以作为有序或无序因素提供给fill=

以下是模仿数据的最小示例:

library(ggplot2)
library(reshape)

x <- c(14,11,9,17)
dfr <- data.frame(COG=letters[1:4], down=1:4, up=x-1:4, tot=x)
dfr <- melt(dfr[,-4], idvar="COG")

ggplot(dfr, aes(x=COG, y=value, fill=factor(variable))) +
  geom_bar(stat="identity") +
  coord_flip() +
  scale_fill_manual(values=c("green3","red3"))

enter image description here

干杯!

编辑:如果您的数据集中的级别混淆了,那么因为factor会在找到时按顺序创建因子级别。要更改订单,请重新排序数据集(正如我所做的那样)并让melt处理它,或者保留它并使用ordered使该因子按照您指定的顺序进行。