Monday, January 28, 2008

Shading overlapping area of curves in R

I was trying to plot figure in R like the one below, which is basically the veto player model of Tsebelis. Based on my knowledge of R now, I encountered 2 major problems:

  1. I don't know if there is a function that can draw archs, or at least partial curves from circles.
  2. I don't know if there is a good way of shading the overlap area in R.
I have struggled for 2 weeks and googled and aske friends for answers. Basically, I just hate to use math to do all the job. Nonetheless, I finished the plot using math a lot with the help of my friend, Charlie.




The basic steps is:
  1. Figure out the angle (theta) to use so that we can get the partial curve from a circle function.
  2. Calculate the intesect points and use acos() or asin() to get the theta where the intersects are and plug it back into the circle functions.
  3. Use polygon() to fill in the shaded area.
The most difficult step is to find intersects. Without right intersects, we cannot get an enclosed poly. Polygon will not work properly.

Today, David Park told me that there was someone who has asked a similar question about how to shade overlap aread of ``circles" in polmeth mailing list. Basically, there is a nice package ``gpclib" in R that can fill in the overlapping areas. I tried it a bit, and it works fine for 2 circles. But if there are three circles, ``gpclib" failed too. (I might have to explore it more)

However, there is one nice function-- get.bbox()-- in ``gpclib" that is very handy. It can help you find out intersects of two circles. So I don't have to go over the math again to find out intersects. R does it for you.

Anway, I kind of agree with what Simon Jackman's suggestion in the polmeth. It is much easier to do this in Adobe illustrator or other graphic tools. But the advantage of using R to make figure like this is that we can make adjustment by altering the code.

The final lesson I got out from this struggle is that math is really important. What is a circle function look like? I had to review my math through google to retrieve the answer. I wish I could have devoted myself more in stuyding it when I was in high school.

P.S Thanks Andy, Aleks, David, and mostly Charlie for their help on making this plot.

1 comment:

Unknown said...

Hi

I am searching for how to calculate the area between two plotted lines and stop by your old posts.

After researching, there seems no established means for finding overlapping areas for non-parametic lines! Any suggestion or directions that I should look into?

Thx

Ma