Matplotlib中圆/面的着色相交 [英] Coloring Intersection of Circles/Patches in Matplotlib
问题描述
以下代码:
# 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()
产生以下情节:
我想指定四个区域的颜色 (1) 背景(当前为白色),(2 和 3)每个单独的事件(非重叠区域,当前为蓝色和红色),以及 (4)相交事件(当前已混合为紫色).例如,我可以为它们着色为红色,绿色,蓝色,黄色-或-我可以给它们提供四个不同的,精确指定的灰度值(更可能是后者).[颜色将根据基础数据的特征生成.]
I would like to specify the colors of the four regions (1) the background (currently white), (2 and 3) each individual event (the non-overlapping areas, currently blue and red), and (4) the intersection event (currently blended to purple). For example, I might color them red, green, blue, yellow -or- I might give them four different, precisely specified grayscale values (the later is more likely). [The colors will be generated based on characteristics of the underlying data.]
我特别不想使用alpha混合来推断"相交处的颜色.我需要明确控制所有四个区域的颜色.
I specifically do not want to use alpha blending to "infer" a color in the intersection. I need to explicitly control the colors of all four regions.
我可以想到一些解决此问题的策略:
I can think of a few strategies to solve this:
- 要求 mpl 提取构成三个不同颜色的图形区域的原始"补丁对象(并执行类似操作以对背景进行操作),然后为它们着色.
- 给定圆圈,手动计算它们的交点并为该交点着色(以某种方式).一点一点地走似乎很丑.
谢谢!
推荐答案
我不确定100%,但是我认为 matplotlib
不具有相交多边形的功能.但是您可以使用 shapely :
I'm not 100% sure but I think matplotlib
does not have the functionality to intersect polygons. But you could 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()
这篇关于Matplotlib中圆/面的着色相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!