[R] 添加誤差棒的分組折線圖:geom_path: Each group consists of only one observation. Do you need to adjust the...


想做一個簡單的分組折線圖,並添加誤差棒,類似下面這樣的:
image.png
用ggplot似乎很簡單就能實現:ggplot+geom_errorbar+geom_line+geom_point,重點在於計算誤差棒。
還是看示例數據吧:
image.png
Type是轉錄和蛋白兩個組學,Region是某個組織的不同區域。想作如上圖的樣子,即不同區域在兩個組學的折線圖分布。

計算誤差需要安裝Rmisc包中的summarySE函數。

# summarySE 計算標准差和標准誤差以及95%的置信區間.
library(Rmisc)
tgc <- summarySE(df2, measurevar="Abundance", groupvars=c("Type","Region"))

數據變成這樣:
image.png
接下來就是作圖了。

# 帶有標准誤差線的折線圖
# 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()

得到警告:
image.png
圖是這樣的,線沒有畫出來。
image.png
查了下網上的答案: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()

果然解決了
image.png
但我還是不明白,為啥網上的示例同樣是兩個分組變量,不用group也能做出來。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM