2015-06-29 67 views
1

我一直在使用matplotlib-venn來生成3組的維恩圖。如下所示。使用Python查找相交值matplotlib-venn

我想問一下如何找到這些集合相交的值。例如,與A集合和B集合相交的384個值是什麼?什麼是交集集合A,集合B和集合C的144個值?值得。

謝謝。

羅德里戈

Matplotlib-venn diagram

+0

的matplotlib - 維恩包是偉大的,但它目前擁有會導致一些設置有[錯誤計數]的問題(https://github.com/konstantint/matplotlib-venn/issues/23)。 –

回答

2

假設使用的是內置的Python set對象,這是非常簡單的,以獲得兩個集合之間的交集。看到這個例子:

>>> a = set(range(30)) 
>>> b = set(range(25,50)) 
>>> a.intersection(b) 
set([25, 26, 27, 28, 29]) 
+0

'intersect = a | b | c'也可以工作。 – Delgan

+1

@Delgan'|'運算符計算聯合,而不是交集。在這種情況下'&'運算符會正確計算交點。 – Brien

+0

Oups,你是對的。 – Delgan

0

我知道這是一個老問題,但我最近在一個類似的問題上工作。爲了未來的訪問者,我在這裏分享我的解決方案。下面的代碼提供了一個解決方案來識別venn圖的每個部分的成員資格。單獨的交叉點是不夠的,你還必須減去不需要的集合。

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