我正在将我的情节转移到ggplot中.几乎没有这个(代码来自前一个问题):

#Set the bet sequence and the % lines
betseq <- 0:700 #0 to 700 bets
perlin <- 0.05 #Show the +/- 5% lines on the graph
#Define a function that plots the upper and lower % limit lines
dralim <- function(stax, endx, perlin) {
lines(stax:endx, qnorm(1-perlin)*sqrt((stax:endx)-stax))
lines(stax:endx, qnorm(perlin)*sqrt((stax:endx)-stax))
}
#Build the plot area and draw the vertical dashed lines
plot(betseq, rep(0, length(betseq)), type="l", ylim=c(-50, 50), main="", xlab="Trial Number", ylab="Cumulative Hits")
abline(h=0)
abline(v=35, lty="dashed") #Seg 1
abline(v=185, lty="dashed") #Seg 2
abline(v=385, lty="dashed") #Seg 3
abline(v=485, lty="dashed") #Seg 4
abline(v=585, lty="dashed") #Seg 5
#Draw the % limit lines that correspond to the vertical dashed lines by calling the
#new function dralim.
dralim(0, 35, perlin) #Seg 1
dralim(36, 185, perlin) #Seg 2
dralim(186, 385, perlin) #Seg 3
dralim(386, 485, perlin) #Seg 4
dralim(486, 585, perlin) #Seg 5
dralim(586, 701, perlin) #Seg 6
Run Code Online (Sandbox Code Playgroud)
我可以证明我有多远(不远):
ggplot(a, aes(x=num,y=s, colour=ss)) +geom_line() +stat_smooth(method="lm", formula="y~poly(x,2)")
Run Code Online (Sandbox Code Playgroud)

要清楚.我正在参考线上绘制我的数据(顶部图像).底部图像显示了我的数据以及我对获取参考线的不良尝试(显然没有效果).
您所做的是将抛物线拟合到数据中,而不是绘制先前定义的抛物线。适应你必须要做的事情并不太难ggplot。
与您相同的开始(尽管betseq实际上没有在任何地方使用)
#Set the bet sequence and the % lines
betseq <- 0:700 #0 to 700 bets
perlin <- 0.05 #Show the +/- 5% lines on the graph
Run Code Online (Sandbox Code Playgroud)
不要用一个绘制线条的函数,而是创建一个返回geom_line您想要的 s (在列表中)的函数。有一个隐含的内容aes(x=x, y=y)将在稍后的声明中给出ggplot,但这定义了构成抛物线的数据点。
#Define a function that plots the upper and lower % limit lines
dralim <- function(stax, endx, perlin) {
c(geom_line(data = data.frame(x=stax:endx,
y=qnorm(1-perlin)*sqrt((stax:endx)-stax))),
geom_line(data = data.frame(x=stax:endx,
y=qnorm(perlin)*sqrt((stax:endx)-stax))))
}
Run Code Online (Sandbox Code Playgroud)
为了避免重复,请定义垂直线 ( edges) 的位置,该位置也可用于定义抛物线 ( ranges) 的左端点和右端点。
edges <- data.frame(x=c(0, 35, 185, 285, 485, 585, 700))
ranges <- data.frame(left = edges$x[-nrow(edges)],
right = edges$x[-1] + 1)
Run Code Online (Sandbox Code Playgroud)
现在构建ggplot. 有一个geom_vline可以绘制所有垂直线(因为我们在单个数据集中定义了位置)。不寻常的步骤是循环遍历 的行(索引)ranges并dralim使用相应的左值和右值(和perlin)进行调用。这将返回 的列表的列表geom_lines,但可以以正常方式将其添加到绘图中,并且所有行都会被添加。最后两个比例调用只是为了设置标签,如果是 y 轴,则设置范围。
ggplot(mapping=aes(x=x, y=y)) +
geom_vline(data=edges, aes(xintercept = x), linetype="dashed") +
lapply(seq_len(nrow(ranges)),
function(r) {dralim(ranges$left[r], ranges$right[r], perlin)}) +
scale_y_continuous("Cumulative Hits", lim=c(-50,50)) +
scale_x_continuous("Trial Number")
Run Code Online (Sandbox Code Playgroud)
