我有data.frame
:
df <- structure(list(sample = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A",
"B", "C"), class = "factor"), replicate = c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L),
treatment = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("V0",
"V2", "V4", "V6"), class = "factor"), mean = c(72.5, 66.4,
60.3, 56.3, 90.7, 86.9, 68.8, 64.6, 73.3, 69.8, 62.3, 68.7,
77.1, 73.6, 65.9, 65.3, 75.7, 73.8, 65.9, 66.8), sd = c(5.4,
6.1, 3.5, 4.7, 1.2, 4.9, 8.4, 6.1, 7.3, 3.5, 5.9, 2.2, 3.2,
3, 3.1, 4.2, 4.2, 2.4, 2.2, 2.6)), .Names = c("sample", "replicate",
"treatment", "mean", "sd"), class = "data.frame", row.names = c(NA,
-20L))
对于某些样本,我有重复,而对于其他我不重复:
> head(df, 15)
sample replicate treatment mean sd
1 A 1 V0 72.5 5.4
2 A 1 V2 66.4 6.1
3 A 1 V4 60.3 3.5
4 A 1 V6 56.3 4.7
5 B 1 V0 90.7 1.2
6 B 1 V2 86.9 4.9
7 B 1 V4 68.8 8.4
8 B 1 V6 64.6 6.1
9 C 1 V0 73.3 7.3
10 C 1 V2 69.8 3.5
11 C 1 V4 62.3 5.9
12 C 1 V6 68.7 2.2
13 C 2 V0 77.1 3.2
14 C 2 V2 73.6 3.0
15 C 2 V4 65.9 3.1
我想在每个sample
值的多面条形图中绘制平均值。我希望在复制时获得分组条> 1.是否可以使用ggplot2?
到目前为止我得到了什么:
g <- ggplot(df, aes(x=treatment, y=mean, fill=sample))
g <- g + geom_bar(position="dodge")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position="dodge")
g <- g + facet_grid(. ~ sample)
g
修改
根据@Tyler Rinker的建议,我得到:
g <- ggplot(df, aes(x=treatment, y=mean, fill=replicate))
g <- g + geom_bar(position="dodge", stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position="dodge", width=0.25)
g <- g + facet_grid(. ~ sample)
但是,我想让'C'样本重复的条形并排显示。
EDIT2 非常接近......
只需添加group
= replicate
:
g <- ggplot(df, aes(x=treatment, y=mean, group=replicate, fill=replicate))
g <- g + geom_bar(position="dodge", stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position="dodge", width=0.25)
g <- g + facet_grid(. ~ sample)
然而,错误条的位置仍然存在问题。我想我必须玩躲闪?但我不知道怎么......
最后......感谢@jorandodge <- position_dodge(width = 0.9)
我检查了除0.9之外的其他值没有导致错误条的正确定位
g <- ggplot(df, aes(x=treatment, y=mean, group=replicate, fill=replicate))
g <- g + geom_bar(position="dodge", stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position=dodge, width=0.25, color="black")
g <- g + facet_grid(. ~ sample)
答案 0 :(得分:3)
试试这个并尝试一下:
dodge <- position_dodge(width = 0.9)
g <- ggplot(df, aes(x=treatment, y=mean, group=replicate, fill=replicate))
g <- g + geom_bar(position=dodge, stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position = dodge,width = 0.25)
g <- g + facet_grid(. ~ sample)
g
我认为每个面板中的不同躲避都会使宽度设置混乱。我必须仔细阅读一些关于躲避细节的信息(这些部分周围有几个人可能比我自己更容易称重......)但我认为时你在每个geom中设置“本地”闪避,ggplot根据每个层中的信息分别决定宽度。所以这里的诀窍似乎是确保“全球”闪避设置。