想做一個簡單的分組折線圖,並添加誤差棒,類似下面這樣的:
用ggplot似乎很簡單就能實現:ggplot+geom_errorbar+geom_line+geom_point
,重點在於計算誤差棒。
還是看示例數據吧:
Type是轉錄和蛋白兩個組學,Region是某個組織的不同區域。想作如上圖的樣子,即不同區域在兩個組學的折線圖分布。
計算誤差需要安裝Rmisc包中的summarySE函數。
# summarySE 計算標准差和標准誤差以及95%的置信區間.
library(Rmisc)
tgc <- summarySE(df2, measurevar="Abundance", groupvars=c("Type","Region"))
數據變成這樣:
接下來就是作圖了。
# 帶有標准誤差線的折線圖
# Standard error of the mean
ggplot(tgc, aes(x=Region, y=Abundance, colour=Type)) +
geom_errorbar(aes(ymin=Abundance-se, ymax=Abundance+se), width=.1) +
geom_line() +
geom_point()
得到警告:
圖是這樣的,線沒有畫出來。
查了下網上的答案:https://blog.csdn.net/tanzuozhev/article/details/51106089
它的數據形式幾乎和我的一樣,但是卻能正常畫出來。
我想了想,是不是分組變量Type和Region沒設為因子,但是設了還是一樣。
查了下錯誤,說是要映射group,令group=1。https://stackoverflow.com/questions/27082601/ggplot2-line-chart-gives-geom-path-each-group-consist-of-only-one-observation
我這里設置了兩組,用group=1或2顯然不行,於是將group映射到變量:
ggplot(tgc, aes(x=Region, y=Abundance, colour=Type, group=Type)) +
geom_errorbar(aes(ymin=Abundance-se, ymax=Abundance+se), width=.1) +
geom_line() +
geom_point()
果然解決了
但我還是不明白,為啥網上的示例同樣是兩個分組變量,不用group也能做出來。