更改堆叠顺序ggplot-geom_bar

时间:2018-10-29 09:24:33

标签: r ggplot2 bar-chart geom-bar

使用geom_bar绘制图形时遇到麻烦。我想要一个像这样的图(见下文),但堆叠顺序相反(浅色在粗体颜色的顶部)。 我希望小条移动到图表顶部

这是图片,下面是我得到的情节。

enter image description here

这是我的数据框:

> gluft
      sex mito nac tissue variable       value        se      int
2  female   WT   0 thorax     GSHr  8056.17054 1591.0030  WT.GSHr
4  female   WT   1 thorax     GSHr  7419.13560 1068.4371  WT.GSHr
6  female   WT  10 thorax     GSHr  7719.67792  133.9016  WT.GSHr
8  female  COX   0 thorax     GSHr 17929.34775  790.0533 COX.GSHr
10 female  COX   1 thorax     GSHr 16382.40832  277.0276 COX.GSHr
12 female  COX  10 thorax     GSHr 17087.65114 4735.9644 COX.GSHr
14 female  BAR   0 thorax     GSHr 15354.80693 3350.8182 BAR.GSHr
16 female  BAR   1 thorax     GSHr 16398.20256 2484.8879 BAR.GSHr
18 female  BAR  10 thorax     GSHr 15129.48573  676.4322 BAR.GSHr
20 female   WT   0 thorax     diff    80.56171 1606.9130  WT.diff
22 female   WT   1 thorax     diff    74.19136 1079.1214  WT.diff
24 female   WT  10 thorax     diff    77.19678  135.2406  WT.diff
26 female  COX   0 thorax     diff   179.29348  797.9538 COX.diff
28 female  COX   1 thorax     diff   163.82408  279.7979 COX.diff
30 female  COX  10 thorax     diff   170.87651 4783.3241 COX.diff
32 female  BAR   0 thorax     diff   129.70685 3368.7446 BAR.diff
34 female  BAR   1 thorax     diff   163.98203 2509.7368 BAR.diff
36 female  BAR  10 thorax     diff   983.08450 1173.1470 BAR.diff

我要做的第一件事是更改因子水平:

gluft$nac <- factor(gluft$nac)    
gluft$int <- factor(gluft$int, levels = c("WT.GSHr","COX.GSHr","BAR.GSHr", "WT.diff","COX.diff","BAR.diff"))

然后我绘制数据:

ggplot(data=gluft, aes(x=nac, y=value, group=mito))+
  geom_bar(aes(fill=int),
           stat = "identity",
           position=position_dodge())+
  scale_fill_manual(
       breaks=c("WT.GSHr","COX.GSHr","BAR.GSHr","WT.diff","COX.diff","BAR.diff"),
        values=c("blue4", "green4","red2","lightblue","lightgreen","pink"))

现在,我尝试来回更改因子水平,但是它什么也没做。

非常感谢!

1 个答案:

答案 0 :(得分:0)

我认为这可以满足您的需求。我只是更改了颜色的顺序

values(...) 

现在,您的图像应该在顶部具有浅色,在底部具有粗体。这是完整的代码。

ggplot(data=gluft, aes(x=nac, y=value, group=mito))+
geom_bar(aes(fill=int),
       stat = "identity",
       position=position_dodge())+
scale_fill_manual(
   breaks=c("WT.GSHr","COX.GSHr","BAR.GSHr","WT.diff","COX.diff","BAR.diff"),
    values=c("lightblue","lightgreen","pink","blue4", "green4","red2"))

欢呼;-)

好,现在我明白了您的要求。我确实找到了不使用ggplot2的解决方案,这可能不是最优雅的方法,但是可以解决问题。我首先将数据集简化为仅包含所需的列。然后,使用tidyr包中的函数spread()将df从长格式更改为宽格式。然后,我使用简单的绘图命令构建了一个堆积的条形图。

library(tidyr)

gluft1 <- gluft[,c("int", "value", "nac")]
data_wide <- spread(gluft1, nac, value)

barplot(as.matrix(data_wide[1:3,2:4]) + as.matrix(data_wide[4:6,2:4]), beside = T, col = c("yellow","lightgreen","pink"))
barplot(as.matrix(data_wide[1:3,2:4]), beside = T, col = c("blue4", "green4","red2"), add = T)

结果应为下图:

enter image description here

然后可以添加您的图例。 希望这会有所帮助。

干杯。