[R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...

想做一个简单的分组折线图,并添加误差棒,类似下面这样的:
[R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...
用ggplot似乎很简单就能实现:ggplot+geom_errorbar+geom_line+geom_point,重点在于计算误差棒。
还是看示例数据吧:
[R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...
Type是转录和蛋白两个组学,Region是某个组织的不同区域。想作如上图的样子,即不同区域在两个组学的折线图分布。

计算误差需要安装Rmisc包中的summarySE函数。

# summarySE 计算标准差和标准误差以及95%的置信区间.
library(Rmisc)
tgc <- summarySE(df2, measurevar="Abundance", groupvars=c("Type","Region"))

数据变成这样:
[R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...
接下来就是作图了。

# 带有标准误差线的折线图
# 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()

得到警告:
[R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...
图是这样的,线没有画出来。
[R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...
查了下网上的答案:https://blog.csdn.net/tanzuozhev/article/details/51106089
它的数据形式几乎和我的一样,但是却能正常画出来。

我想了想,是不是分组变量Type和Region没设为因子,但是设了还是一样。

查了下错误,说是要映射group,令group=1。https://*.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()

果然解决了
[R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...
但我还是不明白,为啥网上的示例同样是两个分组变量,不用group也能做出来。

上一篇:Java.awt.geom.AffineTransform 的使用


下一篇:Arcpy脚本——基于Arcgis实现shp/gdb等到火星/百度坐标系的转换