0
$\begingroup$

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

$\endgroup$
2
  • 1
    $\begingroup$ Are you sure you really meant to change the title to include "Time Series"? The question at hand has nothing intrinsically to do with time series data (unlike your other question). $\endgroup$ – Andy W Aug 29 '11 at 14:14
  • $\begingroup$ @Andy: You are right. I have removed the word time-series. $\endgroup$ – samarasa Aug 29 '11 at 15:41
8
$\begingroup$

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

$\endgroup$
3
  • 1
    $\begingroup$ Thanks for this nice idea. However, I am unable to get the second figure with the code you have provided. Is code for the second graph fine? If not, could you please port correct code. $\endgroup$ – samarasa Aug 28 '11 at 18:24
  • $\begingroup$ @kkp Strange, did you run the first three lines defining x, y, and lims before continuing with the second example? $\endgroup$ – caracal Aug 28 '11 at 18:40
  • $\begingroup$ You are right. I missed a couple of lines. Thanks for your time. $\endgroup$ – samarasa Aug 28 '11 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.