如何在R中绘制成对的组对的条形图?

时间:2016-10-17 18:08:19

标签: r plot graph ggplot2 grouping

我有一个数据框:

Sex Tissue  Stage   Mean    SE
M   X   Larva   9.2 1.3
F   X   Larva   8.4 1.1
M   Y   Larva   9.2 1.4
F   Y   Larva   7.4 0.3
M   X   Pupa    2.1 0.1
F   X   Pupa    5.3 0.2
M   Y   Pupa    9.5 0.5
F   Y   Pupa    2.5 0.1
M   Z   Pupa    6.3 0.4
F   Z   Pupa    9.2 1.1
M   X   Adult   1.2 0.1
F   X   Adult   3.1 0.2
M   Y   Adult   6.3 0.5
F   Y   Adult   9.2 0.6
M   Z   Adult   1.2 0.1
F   Z   Adult   2.3 0.1

如何创建如下所示格式化的条形图(但也有标准误差条),其中所有的M都是相同的颜色,并且所有的F都是相同的颜色?

100 |               _     _ _    _         
    |  _   _       | |  _| | |  | |  _   _  
    | | | | |_     | |_| | | |  | | | | | |  
Mean| | |_| | |   _| | | | | |  | | | | | |_
    | | | | | |  | | | | | | |  | |_| |_| | |
 0  |_|_|_|_|_|__|_|_|_|_|_|_|__|_|_|_|_|_|_|_
       M F M F    M F M F M F    M F M F M F
        X   Y      X   Y   Z      X   Y   Z 
        Larva         Pupa          Adult

数据

dd <- read.table(header = TRUE, text = "Sex Tissue  Stage   Mean    SE
M   X   Larva   9.2 1.3
F   X   Larva   8.4 1.1
M   Y   Larva   9.2 1.4
F   Y   Larva   7.4 0.3
M   X   Pupa    2.1 0.1
F   X   Pupa    5.3 0.2
M   Y   Pupa    9.5 0.5
F   Y   Pupa    2.5 0.1
M   Z   Pupa    6.3 0.4
F   Z   Pupa    9.2 1.1
M   X   Adult   1.2 0.1
F   X   Adult   3.1 0.2
M   Y   Adult   6.3 0.5
F   Y   Adult   9.2 0.6
M   Z   Adult   1.2 0.1
F   Z   Adult   2.3 0.1")

2 个答案:

答案 0 :(得分:1)

这是ggplot2版本。下面的代码在每个条形下方放置“F”或“M”。您也可以选择不包含这些字母,而是在图表旁边放置一个图例。

library(ggplot2)

dd$Stage = factor(dd$Stage, levels=c("Larva","Pupa","Adult"))

pd = position_dodge(0.9)

ggplot(dd, aes(Tissue, Mean, colour=Sex)) + 
  geom_bar(stat="identity", position=pd, fill="grey95", lwd=1) +
  geom_text(aes(label=Sex, y=-0.5), position=pd, size=3.5) +
  geom_errorbar(aes(ymin=Mean - SE, ymax=Mean + SE), width=0.1, position=pd) +
  facet_grid(. ~ Stage, switch="x", scales="free_x", space="free_x") +
  theme_bw() +
  theme(strip.background=element_rect(fill=NA, colour=NA),
        strip.text.x=element_text(size=12)) +
  scale_y_continuous(limits=c(-0.5, max(dd$Mean + dd$SE))) +
  guides(fill=FALSE, colour=FALSE) +
  labs(x="")

enter image description here

答案 1 :(得分:0)

这是一个基础版本

dd$Stage <- factor(dd$Stage, levels = unique(dd$Stage))

bp <- barplot(dd$Mean, space = c(0, diff(as.numeric(dd$Stage)) != 0),
              col = c('tomato','dodgerblue2')[as.numeric(dd$Sex)],
              names.arg = dd$Sex, las = 1)
arrows(bp, dd$Mean, bp, dd$Mean + dd$SE,
       angle = 90, code = 3, xpd = NA, length = .1)

## text
tt <- tapply(bp, list(dd$Tissue, dd$Stage), mean)
text(c(tt), -2.5, labels = rownames(tt), xpd = NA)

tt <- tapply(bp, list(dd$Stage), mean)
text(c(tt), -3.5, labels = names(tt), xpd = NA)

enter image description here