Python Matplotlib Venn diagram

Question:

I want to plot variables that belongs to certain groups.

Say that I have 6 variables that I want to sort into these 3 groups and plot like a venn diagram. I would like to annotate the variable names into the three bubbles.
In this simple example we could say that 1 variable is in group 1, 3 variables in group 2 and 2 variables in group 3.

Could anyone help me with a simple example of how to do it in matplotlib?

Asked By: jonas

||

Answers:

There is a beautiful Venn diagram add-on for matplotlib called matplotlib-venn. It looks like it can be completely customized to do what you are looking for, from the size of the circles (proportional to the set size), to inner and outer labels.

Using the example code on the website gives a plot like:

enter image description here

Edit: Per the comments below the following code gives non-overlapping circles with text using the same library:

import pylab as plt
from matplotlib_venn import venn3, venn3_circles

v = venn3(subsets=(1,1,0,1,0,0,0))
v.get_label_by_id('100').set_text('First')
v.get_label_by_id('010').set_text('Second')
v.get_label_by_id('001').set_text('Third')
plt.title("Not a Venn diagram")
plt.show()

Gives the diagram:

enter image description here

Answered By: Hooked

Here you can just pass the arrays and the overlaps are calculated.

import numpy as np
from matplotlib_venn import venn3

def venn_diagram(a, b, c, labels=['A', 'B', 'C']):

    a = set(a)
    b = set(b)
    c = set(c)

    only_a = len(a - b - c)
    only_b = len(b - a - c)
    only_c = len(c - a - b)

    only_a_b = len(a & b - c)
    only_a_c = len(a & c - b)
    only_b_c = len(b & c - a)

    a_b_c = len(a & b & c)

    venn3(subsets=(only_a, only_b, only_a_b, only_c, only_a_c, only_b_c, a_b_c), set_labels=labels)

a, b, c = np.round(np.random.rand(3, 50000), 5)
venn_diagram(a, b, c)

link to image

Answered By: Soren

simplest way to draw venn diagrams

import matplotlib.pyplot as plt
from matplotlib_venn import venn3

set1 = set(['A', 'B', 'C'])
set2 = set(['A', 'B', 'D'])
set3 = set(['A', 'E', 'F'])

venn3([set1, set2, set3], ('Group1', 'Group2', 'Group3'))

plt.show()

enter image description here

Answered By: bitbang