【问题标题】:Coloring Intersection of Circles/Patches in MatplotlibMatplotlib 中圆/补丁的着色交集
【发布时间】:2015-03-12 21:06:23
【问题描述】:

以下代码:

# 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)交叉点事件(当前混合为紫色)。例如,我可以将它们着色为红色、绿色、蓝色、黄色——或者——我可以给它们四个不同的、精确指定的灰度值(后者更有可能)。 [颜色将根据基础数据的特征生成。]

我特别不想使用 alpha 混合来“推断”交点中的颜色。我需要明确控制所有四个区域的颜色。

我可以想出几个策略来解决这个问题:

  • 让 mpl 提取构成三个不同颜色图形区域的“原始”补丁对象(并执行类似的操作以对背景进行操作),然后为它们着色。
  • 给定圆,手动计算它们的交点并为该交点着色(不知何故)。逐点进行似乎很难看。

谢谢!

【问题讨论】:

    标签: matplotlib


    【解决方案1】:

    我不是 100% 确定,但我认为 matplotlib 没有与多边形相交的功能。但是你可以使用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”解决方案——我更喜欢一个依赖而不是三个。但是,感谢关于匀称和笛卡尔的指针。
    • 好的,我也很感兴趣,我理解您对依赖关系的担忧。但我认为您必须计算交点以生成 3 个单独的多边形(否则您将不得不深入研究 matplotlib 后端并修改渲染,我猜)而且我很确定 matplotlib 没有该功能
    • 所以,我也意识到笛卡尔实际上只有大约 200 行代码。 shapely 看起来是一个非常棒的工具:toblerity.org/shapely/manual.html#spatial-analysis-methods 正是我现在需要的 API。我同意 matplotlib 没有暴露该功能。我想知道是否有任何内部 mpl 函数做类似的事情。
    • 因此,我将该答案标记为已接受,因为我怀疑是否存在纯 matplotlib 方式(缺少手动计算像素)来实现相同的目标。既然你可能感兴趣,这里是我使用的项目:drsfenner.org/blog/2015/02/…
    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多