Search code examples
pythonmatplotlibdata-visualizationmatplotlib-venn

How do I customise the border and background color of my matplotlib-venn plot?


I'm trying to customise the figure area of a venn plot using the plt.figure method, but can't get the expected results.

I'm trying to create a black border and a white background on the plot, but the image still comes out transparent without a border.

I suspect I'm missing something basic with my code, but any pointers would be appreciated. Here's my code.

from matplotlib import pyplot as plt
from matplotlib_venn import venn2, venn2_circles 

# Call 2 group Venn diagram
v = venn2(subsets = (10, 0, 5), set_labels = ('Euler', 'Venn'))
c = venn2_circles(subsets=(10,0,5), linestyle='dashed')

# Format
c[0].set_lw(2.0)
c[0].set_ls('dotted')
c[0].set_alpha(1)
c[0].set_color('#a6cee3')
c[1].set_lw(2.0)
c[1].set_ls('dotted')
c[1].set_alpha(1)
c[1].set_color('#b2df8a')

# Labels
plt.title("Diagrams")
for idx, subset in enumerate(v.subset_labels):
    v.subset_labels[idx].set_visible(False)

# Figure
plt.figure(linewidth=10, edgecolor="black", facecolor="white")
plt.show()

Solution

  • You need to call plt.figure() before you call any drawing function. So, before calling v = venn2(....

    plt.figure() creates a new area to draw or plot something on, and can handle a lot of options. If you don't call plt.figure() or some equivalent function, matplotlib creates a default figure. And when you call plt.figure() later on, matplotlib starts a new empty figure. Normally, matplotlib will show you two windows: the first with the default figure settings, and the second without a plot.

    The complete example, a bit rewritten to make use of loops, would look like:

    from matplotlib import pyplot as plt
    from matplotlib_venn import venn2, venn2_circles
    
    
    plt.figure(linewidth=10, edgecolor="black", facecolor="white")
    
    # Call 2 group Venn diagram
    v = venn2(subsets=(10, 0, 5), set_labels=('Euler', 'Venn'))
    circles = venn2_circles(subsets=(10, 0, 5), linestyle='dashed')
    
    # circle format
    for circle, color in zip(circles, ['#a6cee3', '#b2df8a']):
        circle.set_lw(2.0)
        circle.set_ls('dotted')
        circle.set_alpha(1)
        circle.set_color(color)
    
    # hide unwanted labels
    for label in v.subset_labels:
        label.set_visible(False)
    
    plt.title("Diagrams")
    plt.show()