7

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

KT.
  • 10,815
  • 4
  • 47
  • 71
  • The matplotlib-venn package is great but it currently has an issue that cause some sets to have a [wrong count](https://github.com/konstantint/matplotlib-venn/issues/23). – Franck Dernoncourt Oct 13 '15 at 16:40

2 Answers2

7

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
Steve
  • 1,250
  • 11
  • 25
4

Assuming you are using builtin Python set objects, it is very simple to obtain the intersection between two sets. See this example:

>>> a = set(range(30))
>>> b = set(range(25,50))
>>> a.intersection(b)
set([25, 26, 27, 28, 29])
Blair
  • 6,623
  • 1
  • 36
  • 42
  • 4
    @Delgan The `|` operator computes the union, rather than the intersection. The `&` operator would properly compute the intersection in this case. – Blair Jun 29 '15 at 19:03