Search code examples
python-3.xmatplotlibvenn-diagrammatplotlib-venn

How i can pick(select) venn diagram area


Is it possible to pick or select Venn diagram areas by clicking in python?

from matplotlib import pyplot as plt
import numpy as np
from matplotlib_venn import venn3, venn3_circles
plt.figure(figsize=(4,4))
v = venn3(subsets=(1, 2, 3, 4, 5, 6, 7), set_labels = ('A', 'B', 'C'))
c = venn3_circles(subsets=(1, 2, 3, 4, 5, 6, 7), linestyle='dashed')
plt.title("Sample Venn diagram")
plt.show()

Solution

  • Matplotlib does support some degree of event handling as well as "pick" events for components of a plot (whether it is a Venn diagram or any other type of plot).

    The Venn diagram object returned from the venn3 function contains a field patches, which lists all the PathPatch objects which comprise the diagram. You can make those "pickable" as any other Matplotlib patch objects:

    from matplotlib import pyplot as plt
    import numpy as np
    from matplotlib_venn import venn3
    
    # Create the diagram
    plt.figure(figsize=(4,4))
    v = venn3(subsets=(1, 2, 3, 4, 5, 6, 7), set_labels = ('A', 'B', 'C'))
    plt.title("Sample Venn diagram")
    
    # Make all patches of the diagram pickable
    for p in v.patches:
        if p is not None: p.set_picker(True)
    
    # This is the event handler
    def on_pick(event):
        p = event.artist
        ec = p.get_edgecolor()
        p.set_edgecolor('black' if ec[-1] == 0.0 else 'none')
        plt.gcf().canvas.draw()   # Redraw plot
    
    # Connect event handler
    plt.gcf().canvas.mpl_connect('pick_event', on_pick)
    
    # Show the plot
    plt.show()
    

    The venn3_circles function returns a list of three Circle patches, which are drawn upon the "properly segmented" diagram. You may make them pickable as well, but then you'll need to deal with "pick conflicts" somehow. Hence, in general I'd suggest you use either venn3 (if you need 7 colored patches) or venn3_circles (if you only need the three circles), but not both.