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
818 views
in Technique[技术] by (71.8m points)

r - geom_polygon with multiple hole

I refer to the answer for this question and have additional question.

I have modify the code as below:

library(ggplot2)

ids <- letters[1:2]

# IDs and values to use for fill colour
values <- data.frame(
  id = ids,
  value = c(4,5)
)

# Polygon position
positions <- data.frame(
  id = c(rep(ids, each = 10),rep("b",5)),
  #     shape      hole         shape        hole
  x = c(1,4,4,1,1, 2,2,3,3,2,   5,10,10,5,5, 6,6,7,7,6, 8,8,9,9,8),
  y = c(1,1,4,4,1, 2,3,3,2,2,   5,5,10,10,5, 6,7,7,6,6, 8,9,9,8,8)
)

# Merge positions and values
datapoly <- merge(values, positions, by=c("id"))

chart <- ggplot(datapoly, aes(x=x, y=y)) + 
  geom_polygon(aes(group=id, fill=factor(value)),colour="grey") +
  scale_fill_discrete("Key")

And gives the following output:

enter image description here

There is a line passing through the two colored boxes, which I don't quite like it, how can I remove that? Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The solution I came up with years ago for drawing holes is to make sure that after each hole your x,y coordinates return to the same place. This stops the line buzzing all around and crossing other polygons and leaving open areas that the winding number algorithm doesn't fill (or does fill when it shouldn't).

So, if you have a data set where the first 27 points are your outer, and then you've got three holes of 5, 6, and 7 points, construct a new dataset which is:

newdata = data[c(1:27,28:32,27,33:38,27,39:45,27),] # untested

note how it jumps back to point 27 after each hole. Make sure your holes go in the clockwise direction (I think).

Then draw using newdata but only filling, not drawing outlines. If you want outlines, add them later (using the original data grouped by ring id)

You can sometimes get very very thin artifacts where the outgoing line to the hole isn't quite drawn the same as the incoming line, but they are hardly noticeable. Blame Bresenham.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...