Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...