ggplot绘制误差线,但不绘制R中的实际数据点

时间:2017-04-25 02:38:37

标签: r plot ggplot2 errorbar

我从.csv读取了一个数据帧,如下所示:

valley_cw_summary:

"","times","means","sd"
"1",1,23.7326530612245,0.822951942679513
"2",10,NA,NA
"3",11,27.9811602527283,2.18451736644603
"4",12,NA,NA
"5",13,28.8594485927628,2.47839597165728
"6",14,NA,NA
"7",15,28.5562894887995,2.4613545973872
"8",16,NA,NA
"9",17,26.9750287026406,1.87035639782657
"10",18,NA,NA
"11",19,25.2288340034463,1.0835585618286
"12",2,NA,NA
"13",20,NA,NA
"14",21,24.5269385410684,0.804365453635496
"15",22,NA,NA
"16",23,24.1512923607122,0.806920352501217
"17",24,NA,NA
"18",25,24.0809803921569,0.826911680243558
"19",3,23.5923254472014,0.889646609799541
"20",4,NA,NA
"21",5,23.3741488747836,0.932515616519176
"22",6,NA,NA
"23",7,23.2863296955773,0.982225553711973
"24",8,NA,NA
"25",9,25.4694252873563,1.33025859840695

我尝试使用以下脚本绘制它:

ggplot(data=valley_c_w_summary,aes(x = times,y=means))+
  theme_classic()+
  geom_line(data = valley_c_w_summary,aes(x=times,y=means))+
  geom_errorbar(data=valley_c_w_summary,aes(ymin=means-sd,ymax=means+sd))+
  labs(x="Time",y="Temperature in canopy May to December")

这只绘制误差条(据我所知,以适当的点为中心)。我正在同一个情节上用其他类似的数据框架绘图,它们工作正常,但它们没有任何“NA”,这让我相信它们是罪魁祸首。完整的脚本如下:

ggplot(data=ridge_cw_summary,aes(x = times,y=means))+
  geom_errorbar(data=ridge_c_w_summary,aes(ymin=means-sd,ymax=means+sd),colour="red")+
  geom_line(aes(y=means),colour="red")+
  theme_classic()+
  geom_line(data = valley_c_w_summary,aes(x=times,y=means))+
  geom_errorbar(data=valley_c_w_summary,aes(ymin=means-sd,ymax=means+sd))+
  geom_line(data = edge_c_w_summary,aes(x=times,y=means),colour="blue")+
  geom_errorbar(data=edge_c_w_summary,aes(ymin=means-sd,ymax=means+sd),colour="blue")+
  labs(x="Time",y="Temperature in canopy May to December")

如何让ggplot显示正确的点?

1 个答案:

答案 0 :(得分:1)

Alistaire评论总结了您的答案,您需要将na.omit放在您的数据框周围,同时您不需要在每个geom上调用您的数据,如下所示,我已复制您的数据和将其放入名为 vally_c_w_summary

的数据框中
ggplot(data=na.omit(valley_c_w_summary),aes(x = times,y=means))+
  geom_errorbar(aes(ymin=means-sd,ymax=means+sd),colour="red")+
  geom_line(aes(y=means),colour="blue",size=1)+
  theme_classic()+
  labs(x="Time",y="Temperature in canopy May to December")

我得到了下面的图表,我希望这是你所期待的:

enter image description here

如果您需要近似NA,您可以在zoo库中使用名为 na.approx 的函数。

您的代码如下所示:

library(zoo)
library(ggplot2)
ggplot(data=data.frame(na.approx(valley_c_w_summary)),aes(x = times,y=means))+
  geom_errorbar(aes(ymin=means-sd,ymax=means+sd),colour="red")+
  geom_line(aes(y=means),colour="blue",size=1)+
  theme_classic()+
  labs(x="Time",y="Temperature in canopy May to December")

现在输出会有所不同,误差条增加了。您可以使用NA here

了解na.approx近似的样条和线性变换的文档

enter image description here