matplotlibmatplotlib-venn

How to plot Venn diagram in python for two sets when one set is a subset of another?


I use the following code to plot Venn diagrams. The problem is when one set is a subset of the other the code doesn't work (see the figure). How can I change the following code to make it work when one set is a subset of another? In this case, I expect the red circle to be inside the green circle (the color then probably should be the same as the color of the overlapped area instead of red).

sets = Counter()
sets['01'] = 10
sets['11'] = 5
sets['10']  = 5
setLabels = ['Set 1', 'set 2']

plt.figure()
ax = plt.gca()
v = venn2(subsets = sets, set_labels = setLabels, ax = ax)

h, l = [],[]
for i in sets:
    # remove label by setting them to empty string:
    v.get_label_by_id(i).set_text("")
    # append patch to handles list
    h.append(v.get_patch_by_id(i))
    # append count to labels list
    l.append(sets[i])

#create legend from handles and labels    
ax.legend(handles=h, labels=l, title="Numbers")

plt.title("venn_test")
plt.savefig("test_venn.png")
pdb.set_trace()

enter image description here


Solution

  • You can define sets['10'] = 0, to make the red part (set 1 without set 2) empty. To prevent that empty set from showing up in the legend, slice the handles and labels in the legend call accordingly: ax.legend(handles=h[0:2], labels=l[0:2], title="Numbers")

    So change the code to this:

    sets = Counter()
    sets['01'] = 10
    sets['11'] = 5
    sets['10'] = 0  # set 1 without set 2 is empty
    setLabels = ['Set 1', 'set 2']
    
    plt.figure()
    ax = plt.gca()
    v = venn2(subsets = sets, set_labels = setLabels, ax = ax)
    
    h, l = [],[]
    for i in sets:
        # remove label by setting them to empty string:
        v.get_label_by_id(i).set_text("")
        # append patch to handles list
        h.append(v.get_patch_by_id(i))
        # append count to labels list
        l.append(sets[i])
    
    #create legend from handles and labels, without the empty part    
    ax.legend(handles=h[0:2], labels=l[0:2], title="Numbers")
    
    plt.title("venn_test")
    plt.savefig("test_venn.png")
    pdb.set_trace()