Solved – A better visualization for comparison

data visualizationr

How can I fill with a color in one side of the diagonal of the following graph (only one triangle area) in R? I have used abline(0,1) for drawing the diagonal line. However, as we can see the the diagonal line is not perfect in the left-bottom corner. Could someone help me to draw a perfect diagonal line that starts exactly from the left-bottom corner, please.

enter image description here

Best Answer

I'm not entirely sure if this is what you had in mind, but it could be a start:

x    <- runif(40, 0.2, 0.9)  # x coordinates
y    <- runif(40, 0.2, 0.9)  # y coordinates
lims <- c(0.1, 1)            # axis limits for x and y

With the plot() arguments xaxs="i" and yaxs="i", the axes start and end exactly at the given axis limits. The diagonal line will then be placed where you wanted it. With type="n", the plot is initially empty, so we can add the triangle polygon, and then plot the data points over it.

plot(x, y, type="n", xlim=lims, ylim=lims, xaxs="i", yaxs="i")
polygon(c(lims, rev(lims)), c(lims, 0, 0), col="yellow")  # lower right triangle
abline(0, 1)
points(x, y, pch=20, col="blue")

enter image description here

If you want the data points themselves to have different colors depending on which triangle they lie in, you first have to do a suitable logical comparison to identify these points. In your case, it's just all points with a y-coordinate bigger than the x-coordinate.

below <- y < x            # points in lower right triangle
plot(x, y, type="n", xlim=lims, ylim=lims, xaxs="i", yaxs="i")
points(x[below], y[below], pch=16, col="red")
polygon(c(lims, rev(lims)), c(lims, 1, 1), col="yellow")  # upper left triangle
abline(0, 1)
points(x[!below], y[!below], pch=20, col="blue")

enter image description here