Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - Color a designated area?

I am trying to figure out if there is a way to color only half of a circle that I created using grid.circle.

    library(grid)
    grid.circle(x=.5, y=.5, r=.25,gp=gpar(lwd=10))

I want to make the top half blue, and the bottom half leave white.

Thank you for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using grid.polygon() and some basic trigonometry, you can define a function that'll do this

Some picky care needs to be taken so that the filled semicircle is not distorted when the viewport is non-square. To accomplish this in a way that matches the rules used by grid.circle(), I've set the origin in "npc" units, and the circle radius in "snpc" units. (For more on the meanings of "npc" and "snpc", see ?unit and vignette("grid")):

library(grid)

filledSemiCircle <- function(x_origin, y_origin, radius, fillcolor, top=TRUE) {
    theta <- seq(0, pi, length = 100)
    if(!top) theta <- theta + pi     ## To fill the bottom instead
    x <- unit(x_origin, "npc") + unit(cos(theta) * radius, "snpc")
    y <- unit(y_origin, "npc") + unit(sin(theta) * radius, "snpc")
    grid.polygon(x, y, gp = gpar(fill = fillcolor))
}

filledSemiCircle(0.5, 0.5, 0.25, "dodgerblue")
filledSemiCircle(0.5, 0.5, 0.25, "gold", top=FALSE)
grid.circle(x = .5, y=.5, r=.25,gp=gpar(lwd=10))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...