Coloring intersection circles / patches in Matplotlib

The following code:

# in ipython notebook, enable inline plotting with: # %pylab inline --no-import-all import matplotlib.pyplot as plt # create some circles circle1 = plt.Circle((-.5,0), 1, color='r', alpha=.2) circle2 = plt.Circle(( .5,0), 1, color='b', alpha=.2) # add them to the plot (bad form to use ;, but saving space) # and control the display a bit ax = plt.gca() ax.add_artist(circle1); ax.add_artist(circle2) ax.set_xlim(-2, 2); ax.set_ylim(-2, 2) ax.set_aspect('equal') # display it plt.plot() 

It produces the following graph:

Vennish diagram

I would like to indicate the colors of the four areas (1) the background (currently white), (2 and 3) each individual event (non-overlapping areas, currently blue and red) and (4) the intersection event (currently mixed with purple ) For example, I could color them red, green, blue, yellow, or — I could give them four different, precisely defined values ​​for shades of gray (a later version). [Colors will be generated based on the characteristics of the underlying data.]

I specifically do not want to use alpha blending to “bring out” the color at the intersection. I need to explicitly control the colors of all four areas.

I can come up with several strategies to solve this problem:

  • Ask mpl to extract the “primitive” patch objects that make up the three clearly colored graphic areas (and do something similar to working in the background), and then color them.
  • Given the circles, manually calculate their intersection and the color of that intersection (somehow). Jumping over points seems ugly.

Thanks!

+6
source share
1 answer

I am not 100% sure, but I think that matplotlib does not have functions for crossing polygons. But you can use shapely :

 import shapely.geometry as sg import matplotlib.pyplot as plt import descartes # create the circles with shapely a = sg.Point(-.5,0).buffer(1.) b = sg.Point(0.5,0).buffer(1.) # compute the 3 parts left = a.difference(b) right = b.difference(a) middle = a.intersection(b) # use descartes to create the matplotlib patches ax = plt.gca() ax.add_patch(descartes.PolygonPatch(left, fc='b', ec='k', alpha=0.2)) ax.add_patch(descartes.PolygonPatch(right, fc='r', ec='k', alpha=0.2)) ax.add_patch(descartes.PolygonPatch(middle, fc='g', ec='k', alpha=0.2)) # control display ax.set_xlim(-2, 2); ax.set_ylim(-2, 2) ax.set_aspect('equal') plt.show() 

enter image description here

+7
source

Source: https://habr.com/ru/post/981003/


All Articles