Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding intersect values using Python matplotlib-venn

I've been using matplotlib-venn to generate a venn diagram of 3 sets. Shown below.

I wanted to ask how can find the values of the intersects of these sets. For example, what are the 384 values that intersect set A and set B? What are the 144 values that intersect set A, set B, and set C? and so worth.

Thank you.

Rodrigo

Matplotlib-venn diagram

like image 268
Rodrigo Matus-Nicodemos Avatar asked Jun 29 '15 18:06

Rodrigo Matus-Nicodemos


1 Answers

I know this is an old question, but I recently worked on a similar problem. For the sake of future visitors, I'm sharing my solution here. The code below provides a solution to identify the membership of every section of the venn diagram. Intersections alone are not sufficient, you must also subtract the unwanted sets.

def get_venn_sections(sets):
    """
    Given a list of sets, return a new list of sets with all the possible
    mutually exclusive overlapping combinations of those sets.  Another way
    to think of this is the mutually exclusive sections of a venn diagram
    of the sets.  If the original list has N sets, the returned list will
    have (2**N)-1 sets.

    Parameters
    ----------
    sets : list of set

    Returns
    -------
    combinations : list of tuple
        tag : str
            Binary string representing which sets are included / excluded in
            the combination.
        set : set
            The set formed by the overlapping input sets.
    """
    num_combinations = 2 ** len(sets)
    bit_flags = [2 ** n for n in range(len(sets))]
    flags_zip_sets = [z for z in zip(bit_flags, sets)]

    combo_sets = []
    for bits in range(num_combinations - 1, 0, -1):
        include_sets = [s for flag, s in flags_zip_sets if bits & flag]
        exclude_sets = [s for flag, s in flags_zip_sets if not bits & flag]
        combo = set.intersection(*include_sets)
        combo = set.difference(combo, *exclude_sets)
        tag = ''.join([str(int((bits & flag) > 0)) for flag in bit_flags])
        combo_sets.append((tag, combo))
    return combo_sets
like image 200
Steve Avatar answered Oct 05 '22 07:10

Steve