— An example of creating Two-way Venn diagrams with Python codes
Venn diagrams were firstly introduced by John Venn in 1880 and used to illustrate simple set relationships in the field of probability, logic, statistics, linguistics, and computer science etc. They are also called primary diagram, set diagram, or logic diagram and consisted of multiple overlapping circles.
The package we are using to create Venn diagrams is Matplotlib-venn (https://pypi.org/project/matplotlib-venn/), which is a third-party one dependent on Numpy, Scipy and Matplotlib. The installation is simply typing the following code in the terminal:
pip install matplotlib-venn
After we finish install the package, we can get it started now. Suppose we have two sets, A and B:
A = set([‘A’, ‘B’, ‘C’])
B = set([‘C’, ‘D’,’ E’, ‘F’, ‘G’])
Example1: Two-way Venn diagrams (Unweighted)
from matplotlib_venn import venn2_unweighted
# method 1v1 = venn2_unweighted(subsets=[A, B],set_labels=['set A', 'set B'], set_colors=['purple', 'skyblue'])
It is obvious that there is one element that is commonly exists in both A and B sets, 2 and 4 elements uniquely exist in A and B set individually, so we can use these quantities directly by giving a list of subset sizes:
# method 2# list of subset sizes: (left_unique, right_unique, shared_ones)v2 = venn2_unweighted(subsets = (2, 4, 1), set_labels=['set A', 'set B'], set_colors=['purple', 'skyblue'])
Or we could also use these quantities by passing a dictionary of subset sizes:
# method 3# dic of subset sizes: ('10': left_unique, '01': right_unique, '11': shared_ones). Note that '10','01' and '11' are the keys of the positions and their names cannot be changed.v3= venn2_unweighted(subsets = {'10': 2, '01': 4, '11': 1}, set_labels=['set A', 'set B'], set_colors=['purple', 'skyblue'])
Example2: Two-way Venn diagrams (Weighted)
from matplotlib_venn import venn2# method 1v1 = venn(subsets=[A, B],set_labels=['set A', 'set B'], set_colors=['purple', 'skyblue'])# method 2
# the order of these quantities are: (left_unique, right_unique, shared_ones)v2 = venn2(subsets = (2, 4, 1), set_labels=['set A', 'set B'], set_colors=['purple', 'skyblue'])
# method 3
# dic of subset sizes: ('10': left_unique, '01': right_unique, '11': shared_ones). Note that '10','01' and '11' are the keys of the positions and their names cannot be changed.v3= venn2(subsets = {'10': 2, '01': 4, '11': 1}, set_labels=['set A', 'set B'], set_colors=['purple', 'skyblue'])
Customize it:
- Example of change font sizes:
v1 = venn2(subsets=[A, B],
set_labels=['set A', 'set B'],
set_colors=['purple', 'skyblue'])for text in v1.set_labels:
text.set_fontsize(7)
for x in range(len(v1.subset_labels)):
if v1.subset_labels[x] is not None:
v1.subset_labels[x].set_fontsize(7)