A Venn diagram is a graphical representation that shows the relationships among different sets. It uses overlapping circles to show common and unique elements across various sets. For example:
- Each circle represents a distinct set.
- The overlapping areas indicate elements that are shared between the sets.
- The non-overlapping areas represent elements that are unique to each set.
In this blog, we will learn how to generate Venn diagrams using Python. The code uses the matplotlib_venn
library to generate the Venn diagram using two sets and the matplotlib
library to display the Venn diagram.
Here is the complete Python code to generate a Venn diagram:
from matplotlib_venn import venn2
import matplotlib.pyplot as plt
import argparse
def generate_venn_diagram(a, b):
"""
this function generates venn diagram using two given sets
"""
# Create the Venn diagram
venn = venn2([a, b], set_labels=('Set A', 'Set B'))
# Customize colors
if len(a) > 0:
venn.get_patch_by_id('10').set_color('blue') # Color for A only
if len(b) > 0:
venn.get_patch_by_id('01').set_color('red') # Color for B only
if len(a.intersection(b)) > 0:
venn.get_patch_by_id('11').set_color('yellow') # Color for A ∩ B
# Set title and display
plt.title("Venn Diagram of Sets A and B")
plt.show()
def parse_set(set_str):
"""
convert a string representation of a set into a Python set.
"""
return set(map(int, set_str.strip("{}").split(',')))
def main():
"""
python code to generate venn diagram using two given sets
"""
# set up argument parser
parser = argparse.ArgumentParser(description="Generate Venn diagram.")
parser.add_argument("-set_a", type=str, required=True, help="First set (e.g., '{1,2,3,4}')")
parser.add_argument("-set_b", type=str, required=True, help="Second set (e.g., '{3,4,5,6}')")
args = parser.parse_args()
# Parse the sets
a = parse_set(args.set_a)
b = parse_set(args.set_b)
# generate venn diagram
generate_venn_diagram(a, b)
if __name__ == "__main__":
main()
To run this code, save it as venn_diag.py
(or any preferred name you like) and execute it from the command line with two sets as arguments, as shown below:
python venn_diag.py -set_a "{1,2,3,7,8}" -set_b "{4,5,6,7,8}"
As shown above, you need to provide two sets as strings. The code converts the string sets to Python sets before applying the venn2()
function. The above command generates the following Venn diagram showing the number of unique elements in sets A and B, and the number of common elements between A and B.

Please let me know in the comments if you encounter any issues with the code.