geom_polygon with multiple hole

空扰寡人 提交于 2019-12-18 09:24:18

问题


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:

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


回答1:


Try this one

ggplot(datapoly, aes(x=x, y=y)) +
  geom_polygon(aes(group=id, fill=factor(value))) +
  scale_fill_discrete("Key")




回答2:


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.



来源:https://stackoverflow.com/questions/12047643/geom-polygon-with-multiple-hole

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!