Matplotlib Venn diagram with legend

6.1k views Asked by At

I'm using the matplotlib-venn packages for drawing venn diagrams in python. This packages works nicely for drawing Venn diagrams with two or three sets. However, when one of the sets is much larger than the others, the counts in the smaller circles can get close or overlap. Here's an example.

from collections import Counter
import matplotlib.pyplot as plt
from matplotlib_venn import venn2, venn3

sets = Counter()
sets['01'] = 3000
sets['11'] = 3
sets['10']  = 5
setLabels = ['set1', 'set2']

plt.figure()
ax = plt.gca()
v = venn2(subsets = sets, set_labels = setLabels, ax = ax)
plt.title('Venn Diagram')
plt.show()

enter image description here

What I'm looking to do is move the counts (in this case, 3000, 3, and 5) to a legend with colors matching those in the diagram. Wasn't sure how to do this with matplotlib_venn.

1

There are 1 answers

0
ImportanceOfBeingErnest On BEST ANSWER

You may replace the labels for the venn diagram with empty strings and instead create a legend from the patches of the venn and the respective counts as follows:

from collections import Counter
import matplotlib.pyplot as plt
from matplotlib_venn import venn2, venn3

sets = Counter()
sets['01'] = 3000
sets['11'] = 3
sets['10']  = 5
setLabels = ['set1', 'set2']

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="counts")

plt.title('Venn Diagram')
plt.show()

enter image description here