R 用ggplot绘制水平线

R 用ggplot绘制水平线,r,ggplot2,R,Ggplot2,我想用ggplot2在折线图中画一条红色的水平平均线,但我不知道怎么做。它不应表示列E的值的平均值 我证明了这一点,但它不起作用: ggplot(data = df3, aes(x = df3$timestamp, y = df3[,1], group = 1)) + geom_line() + ylab("values") + xlab("time") + geom_hline(yintercept=mean(df3[,1])) 数据帧称为df3,x行时间序列是列时间

我想用
ggplot2
在折线图中画一条红色的水平平均线,但我不知道怎么做。它不应表示列
E
的值的平均值

我证明了这一点,但它不起作用:

ggplot(data = df3, aes(x = df3$timestamp, y = df3[,1], group = 1)) + 
  geom_line() + 
  ylab("values") + 
  xlab("time") + 
  geom_hline(yintercept=mean(df3[,1]))
数据帧称为
df3
,x行时间序列是列
时间戳
,y行是列度量
E

这里,数据帧头:

           E               timestamp
11 -22.30933 2015-02-09 09:05:00.712
14 -22.17142 2015-02-09 09:06:00.703
17 -21.24673 2015-02-09 09:07:00.703
20 -21.58154 2015-02-09 09:08:00.702
23 -21.07082 2015-02-09 09:09:00.702
26 -22.49973 2015-02-09 09:10:00.702

一般来说,您应该能够使用
geom_行(stat=“hline”,yintercept=“mean”)
,如下例所示:

require(ggplot2)
ggplot(mtcars, aes(x = wt, y=mpg)) + 
  geom_point() +
  geom_line(stat = "hline", yintercept = "mean", colour = "red")

如果将数据设置为
df3
,则不必在
aes
中的变量名前面使用
df3$
。所以:
aes(x=timestamp,y=df3[,1],group=1)
很好。可复制的示例会很好。为什么要使用
df3[,1]
两次?因此,一次用于
geom_line()
,第二次用于
geom_hline()
?查看
df3
的外观可能会很有用。您的代码运行良好,只需添加颜色:
geom_hline(yintercept=mean(df3[,1]),col=“red”)