2011-05-27 15 views
6

Me gustaría añadir una línea parábola que indica los límites de confianza del 95% para esta parcela lanzamiento de la moneda usando R:Añadir límites de confianza del 95% al ​​terreno acumulada

x <- sample(c(-1,1), 60000, replace = TRUE) 
plot.ts(cumsum(x), ylim=c(-250,250)) 

Aquí está un ejemplo de lo que estoy buscando : graph

ACTUALIZACIÓN: @ bill_080 tiene una respuesta excelente. Sin embargo ya he calculado 100.000 lanzamientos de la moneda:

str(100ktoss) 
num [1:100000] -1 1 1 1 -1 -1 1 -1 -1 -1 ... 

y realmente quiero añadir sólo el límite del 95% a la parcela: toss

plot.ts(cumsum(100ktoss)) 

tardó varias horas para calcular mis lanzamientos de moneda 100K y cuando trato de replicar con el código de @ bill_080 me quedo sin memoria (para 100,000).

ACTUALIZACIÓN FINAL: Bien. Último problema Tengo un gráfico de varias rondas de aciertos acumulativos, en un solo gráfico con el inicio de cada ronda fijado a cero (en realidad 1 o -1 dependiendo de si fue un triunfo o una derrota).

>str(1.ts) 
Time-Series [1:35] from 1 to 35: 1 2 1 2 3 4 5 4 5 6 ... 
>str(2.ts) 
Time-Series [1:150] from 36 to 185: -1 0 1 0 -1 -2 -1 0 1 2 ... 

Me gustaría agregar el mismo límite de 95% para cada segmento, como así. Ahora resuelto:

@ bill_080 Muchas gracias. Este es el producto final:

cum

Respuesta

9

probar esto. Todos los bucles son for bucles, por lo que puede agregar fácilmente más cálculos.

#Set the number of bets and number of trials and % lines 
numbet <- 6000 #6000 bets 
numtri <- 1000 #Run 1000 trials of the 6000 bets 
perlin <- 0.05 #Show the +/- 5% lines on the graph 
rantri <- 60 #The 60th trial (just a random trial to be drawn) 

#Fill a matrix where the rows are the cumulative bets and the columns are the trials 
xcum <- matrix(NA, nrow=numbet, ncol=numtri) 
for (i in 1:numtri) { 
    x <- sample(c(-1,1), numbet, replace = TRUE) 
    xcum[,i] <- cumsum(x) 
} 

#Plot the trials as transparent lines so you can see the build up 
matplot(xcum, type="l", xlab="Number of Bets", ylab="Cumulative Sum", main="Cumulative Results", col=rgb(0.01, 0.01, 0.01, 0.02)) 
grid() 

#Sort the trials of each bet so you can pick out the desired % 
xcumsor <- xcum 
for (i in 1:numbet) { 
    xcumsor[i,] <- xcum[i,order(xcum[i,])] 
} 

#Draw the upper/lower limit lines and the 50% probability line  
lines(xcumsor[, perlin*numtri], type="l", lwd=2, col=rgb(1, 0.0, 0.0)) #Lower limit 
lines(xcumsor[, 0.5*numtri], type="l", lwd=3, col=rgb(0, 1, 0.0)) #50% Line 
lines(xcumsor[, (1-perlin)*numtri], type="l", lwd=2, col=rgb(1, 0.0, 0.0)) #Upper limit 

#Show one of the trials 
lines(xcum[, rantri], type="l", lwd=1, col=rgb(1, 0.8, 0)) #Random trial 

#Draw the legend 
legend("bottomleft", legend=c("Various Trials", "Single Trial", "50% Probability", "Upper/Lower % Limts"), bg="white", lwd=c(1, 1, 3, 2), col=c("darkgray", "orange", "green", "red")) 

enter image description here

EDIT 1 ==================================== ======================

Si solo está tratando de dibujar las líneas +/- 5%, es solo una función de raíz cuadrada. Aquí está el código:

#Set the bet sequence and the % lines 
betseq <- 1:100000 #1 to 100,000 bets 
perlin <- 0.05 #Show the +/- 5% lines on the graph 

#Calculate the Upper and Lower limits using perlin 
#qnorm() gives the multiplier for the square root 
upplim <- qnorm(1-perlin)*sqrt(betseq) 
lowlim <- qnorm(perlin)*sqrt(betseq) 

#Get the range for y 
yran <- range(upplim, lowlim) 

#Plot the upper and lower limit lines 
plot(betseq, upplim, ylim=yran, type="l", xlab="", ylab="") 
lines(betseq, lowlim) 

enter image description here

Editar 2 ================================ ==================

Para agregar las parábolas en las ubicaciones correctas, probablemente sea más fácil si define una función. Tenga en cuenta que debido a que la nueva función (dralim) usa lines, la trama debe existir antes de llamar al dralim. Usando algunas de las mismas variables que el código en Edición 1:

#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 

enter image description here

+0

@ bill_080 muy, muy agradable. Si miras mi perfil verás que tengo algo para las tramas de lanzamiento de moneda y que la tuya es una belleza. Lo único es que quizás sea demasiado complicado para mí. :) –

+1

@RSoul, agregué otra gráfica con el código asociado. Muestra los límites superior/inferior para las líneas del 5%.Es solo la raíz cuadrada del número de apuesta multiplicado por el% de probabilidad que desea. En el código, la función 'qnorm()' te da el multiplicador. Para 5%, 'qnorm (0.05)' da -1.644 y 'qnorm (0.95)' da 1.644. –

+0

@ bill_080 Eso es excelente. Exactamente lo que quería. Es por eso que he reconocido a los usuarios de StackOverflow.com en mi tesis. Muchas gracias. Puedo usar tu argumento más interesante. Todavía tengo que decidir. –

Cuestiones relacionadas