[R] Shading specific region in R

S Ellison
Tue, 27 Mar 2018 15:44:21 -0000

> Following the given codes below, I generated a plot that has 6 regions
around a
> center point (IL), with 5 regions containing
>
> a point (L1, L2 to L5) and sixth vacant region. I want background of all
the filled
> regions turned "green", while "red" for the
>
> vacant region. Can it be done through a quicker way?

You can certainly reduce the number of lines of code.
And you can shade a region using polygon()
Code to replace yours and add polygon below, as an example, commented.

#########
plot(1:10,type="n",xlab=expression("D"[a]),ylab=expression("D"[b]),cex.lab=1.3,
mgp = c(2, 1, 0))
	#type="n" supporesses points - no need to draw them at all
pu <- par("usr") #saves typing later

#shading regions is easiest using polygon()
#You also need the shading first, to draw on top.
#since you're shading everything except one region, start with a single
background colour.
rect(pu[1],pu[3],pu[2],pu[4],col = "lightgreen")

#construct and add the shaded region
xrange <- pu[3]-pu[1]
yrange <- pu[4]-pu[2]

x0 <- 5
y0 <- 5

x.poly <- c(x0, pu[1], pu[1], x0 - (y0 - pu[3]) / tan(pi/3), x0)
y.poly <- c(y0, y0, pu[3], pu[3], y0)

polygon(x.poly, y.poly, col="pink") #shaded region

#Then there are simplifications using vectorisation:
# points(), text() and segments() are vectorised so you only need one call to
each.
px <- c(5,5,5,2,9,8)
py <- c(5,9,1,7,4,8)
p.cols <- c("green", rep("yellow", 5))

points(px, py, pch=19, col=p.cols)

# You can put text at the point locations with a simple offset
# You can also construct text expressions by substitution
for(i in 1:6)
         text(px[i]+0.5, py[i]+0.3, bquote(L[.(i)]), cex=1.2)

# segments() takes vectors too.
# The following is just an example, assuming you want equally spaced lines at
# 60 degree intervals, all originating from a centre (x0=5, y0=5)

seglen <- 10 #arbitrary length, relying on clipping to the plot region

segments(x0, y0, x0+seglen * cos( (0:5) * pi/3), y0 +seglen * sin( (0:5) * pi/3)
)



*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}