R - shade area between two crossing lines with different colors

前端 未结 2 1388
旧时难觅i
旧时难觅i 2021-01-20 17:20

I have a matrix (named ichimoku) with 516 rows and 2 columns ,each one of them containing values to be plotted, the goal is to recreate the clouds for the Ichimoku strategy.

2条回答
  •  太阳男子
    2021-01-20 17:29

    Here is some code that works for a simple version of your problem, in which the lines only cross once. I haven't tested it for repeated crossings, however.

    # Make toy data
    ichimoku <- data.frame(senkouA = rep(10, 10), senkouB = c(3, 5, 4, 7, 10, 11, 15, 12, 13, 14))
    
    # Make indices for the conditions that define the fill colors. They need to intersect for the polygons to connect.
    index.green = with(ichimoku, as.logical(senkouA >= senkouB))
    index.red = with(ichimoku, as.logical(senkouA <= senkouB))
    
    # Make the line plot
    matplot(ichimoku, lty=1, lwd=1, pch=20, type="l", col=c("red","blue"))
    
    # Now add polygons with fill color based on those conditions by subsetting the task using the indices.
    with(ichimoku, polygon(x = c(seq(length(senkouA))[index.green], rev(seq(length(senkouA))[index.green])),
        y = c(senkouB[index.green], senkouA[index.green]), col = "green"))
    with(ichimoku, polygon(x = c(seq(length(senkouA))[index.red], rev(seq(length(senkouA))[index.red])),
        y = c(senkouB[index.red], senkouA[index.red]), col = "red"))
    

    Here's my result:

提交回复
热议问题