0

我正在寻找一个非常具体的问题的答案。我在他们的页面上找到了在 ggplot2 中的绘图上叠加函数的方法:http ://docs.ggplot2.org/current/stat_function.html

但就我而言,我有一个在 Y 轴上使用时间的图。我的数据是:

dput(flN)
structure(list(eCenter = c(52, 85, 141, 227, 645), eLow = c(42, 
64, 112, 178, 546), eHigh = c(65, 112, 178, 290, 761), arrivalTime = structure(c(957173699, 
957173635, 957173496, 957173418, 957173338), class = c("POSIXct", 
"POSIXt"), tzone = ""), timeError = c(6.436288, 2.075383, 1.321365, 
1.270163, 3.422232), vCenter = c(125839365.727275, 154297213.515671, 
186197068.826928, 216301111.588418, 268912290.324273), vLow = c(114601800.781488, 
137454241.369541, 171493844.86893, 201095521.048661, 262431046.389897
), vHigh = c(138347098.798059, 171493844.86893, 201095521.048661, 
230862999.254391, 274537514.959924)), .Names = c("eCenter", "eLow", 
"eHigh", "arrivalTime", "timeError", "vCenter", "vLow", "vHigh"
), row.names = c("E1'", "E2'", "E3'", "E4'", "FP5'"), class = "data.frame")

看起来像:

> flN
     eCenter eLow eHigh         arrivalTime timeError   vCenter      vLow     vHigh
E1'       52   42    65 2000-05-01 10:34:59  6.436288 125839366 114601801 138347099
E2'       85   64   112 2000-05-01 10:33:55  2.075383 154297214 137454241 171493845
E3'      141  112   178 2000-05-01 10:31:36  1.321365 186197069 171493845 201095521
E4'      227  178   290 2000-05-01 10:30:18  1.270163 216301112 201095521 230862999
FP5'     645  546   761 2000-05-01 10:28:58  3.422232 268912290 262431046 274537515

其他数量是:

m = 574.2538
c = 3E8
y0 = flN$arrivalTime - m*c/flN$vCenter
y01 = y0[1]

我尝试的代码是:

#this works and plots a part of what I want:
p <- ggplot(flN, aes(x=c/vCenter, y=arrivalTime)) + geom_point(aes(y=arrivalTime)) + geom_errorbarh(aes(xmin=c/vHigh, xmax=c/vLow)) + xlim(0, 3)  + ylim(as.POSIXct('2000/05/01 10:20'), as.POSIXct('2000/05/01 10:40')) 

# the function I want to plot. It's a simple straight line function
test <- function(x) {y01 +m*x}

# the code to plot this function over my previous plotted data that doesn't work:
p + stat_function(fun = test, colour="#F8766D", linetype="dashed")
> Error: Discrete value supplied to continuous scale

现在,从错误来看,我认为问题一定是使用 Y 的时间轴,但我该如何解决这部分问题?

4

1 回答 1

2

似乎会stat_function()给出错误,因为它找不到变量y01并且m在全局环境中定义并计算其他内容或给出一些不连续的值。解决此问题的一种方法是test()通过添加y01m作为参数然后stat_function()添加来修改您的函数args=c(y01,m)- 这将确保正确找到和使用参数。我也ylim()从你的ggplot()电话中删除了(至少对我来说它在数据区域之外)。

test <- function(x,y01,m) {y01 +m*x}

p <- ggplot(flN, aes(x=c/vCenter, y=arrivalTime)) + 
     geom_point(aes(y=arrivalTime)) + 
     geom_errorbarh(aes(xmin=c/vHigh, xmax=c/vLow)) + xlim(0, 3)

p + stat_function(fun = test,args=c(y01,m), colour="#F8766D", linetype="dashed")

在此处输入图像描述

于 2013-04-11T06:09:11.550 回答