代码之家  ›  专栏  ›  技术社区  ›  Swike

如何在matplotlib中为重叠的圆上色?

  •  0
  • Swike  · 技术社区  · 1 年前

    以下代码:

    # 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()
    

    生成以下绘图:

    VennishDiagram

    我想指定四个区域的颜色(1)背景(当前为白色),(2和3)每个单独事件(非重叠区域,当前为蓝色和红色),以及(4)交叉事件(当前混合为紫色)。例如,我可能会将它们涂成红色、绿色、蓝色、黄色,或者-我可能会给它们四个不同的、精确指定的灰度值(更可能是后者)。[颜色将根据基础数据的特征生成。]

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

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

    • 请mpl提取组成三个颜色明显的图形区域的“原始”补丁对象(并在背景上执行类似的操作),然后对它们进行着色。
    • 给定圆,手动计算它们的交点并为交点着色(不知何故)。
    0 回复  |  直到 1 年前
        1
  •  18
  •   sappjw hitzg    2 年前

    我不是百分之百确定,但我认为 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()
    

    enter image description here