Python matplotlib可視化之繪制韋恩圖

本文速覽

2組數據venn

3組數據venn 

4組數據venn 

5組數據venn圖

6組數據venn 

python中Matplotlib並沒有現成的函數可直接繪制venn圖, 不過已經有前輩基於matplotlib.patches及matplotlib.path開發瞭兩個輪子:

matplotlib_venn【2~3組數據,比較多博客介紹】:https://github.com/konstantint/matplotlib-venn

pyvenn【2~6組數據】:https://github.com/tctianchi/pyvenn

1、 matplotlib_venn

該模塊包含'venn2', 'venn2_circles',  'venn3', 'venn3_circles'四個關鍵函數,這裡主要詳細介紹'venn2','venn3'同理。

(1)2組數據venn圖

matplotlib_venn.venn2(subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None)

繪圖數據格式

subsets參數接收繪圖數據集,以下5種方式均可以,註意細微異同。

#導入依賴packages
import matplotlib.pyplot as plt
from matplotlib_venn import venn2,venn2_circles#記得安裝matplotlib_venn(pip install matplotlib_venn 或者conda install matplotlib_venn)
 
 
# subsets參數
#繪圖數據的格式,以下5種方式均可以,註意異同
subset = [[{1,2,3},{1,2,4}],#列表list(集合1,集合2)
          ({1,2,3},{1,2,4}),#元組tuple(集合1,集合2)
          {'10': 1, '01': 1, '11': 2},#字典dict(A獨有,B獨有,AB共有)
          (3, 3, 2),####元組tuple(A有,B有,AB共有),註意和其它幾種方式的異同點
          [3,3,2]#列表list(A有,B有,AB共有)           
         ]
for i in subset:
    my_dpi=100
    plt.figure(figsize=(500/my_dpi, 500/my_dpi), dpi=my_dpi)
    g=venn2(subsets=i)#默認數據繪制venn圖,隻需傳入繪圖數據
    plt.title('subsets=%s'%str(i))
    plt.show()

一些簡單參數介紹 

my_dpi=150
plt.figure(figsize=(580/my_dpi, 580/my_dpi), dpi=my_dpi)#控制圖尺寸的同時,使圖高分辨率(高清)顯示
g=venn2(subsets = [{1,2,3},{1,2,4}], #繪圖數據集
        set_labels = ('Label 1', 'Label 2'), #設置組名
        set_colors=("#098154","#c72e29"),#設置圈的顏色,中間顏色不能修改
        alpha=0.6,#透明度
        normalize_to=1.0,#venn圖占據figure的比例,1.0為占滿
       )
plt.show()

所有圈外框屬性設置 

my_dpi=150
plt.figure(figsize=(580/my_dpi, 580/my_dpi), dpi=my_dpi)
g=venn2(subsets = [{1,2,3},{1,2,4}],
        set_labels = ('Label 1', 'Label 2'),
        set_colors=("#098154","#c72e29"),
        alpha=0.6,
        normalize_to=1.0,
       )
g=venn2_circles(subsets = [{1,2,3},{1,2,4}], 
        linestyle='--', linewidth=0.8, color="black"#外框線型、線寬、顏色
       )
plt.show()

單個圈特性設置

g.get_patch_by_id('10')返回一個matplotlib.patches.PathPatch對象,有諸多參數可個性化修改 ,詳細見matplotlib官網。

my_dpi=150
plt.figure(figsize=(550/my_dpi, 550/my_dpi), dpi=my_dpi)
 
g=venn2(subsets = [{1,2,3},{1,2,4}], 
        set_labels = ('Label 1', 'Label 2'), 
        set_colors=("#098154","#c72e29"),
        alpha=0.6,
        normalize_to=1.0,
       )
g.get_patch_by_id('10').set_edgecolor('red')#左圈外框顏色
g.get_patch_by_id('10').set_linestyle('--')#左圈外框線型
g.get_patch_by_id('10').set_linewidth(2)#左圈外框線寬
g.get_patch_by_id('01').set_edgecolor('green')#右圈外框顏色
g.get_patch_by_id('11').set_edgecolor('blue')#中間圈外框顏色
plt.show()

單個圈文本設置

g.get_label_by_id('10') 返回一個matplotlib.text.Text對象,有諸多參數可個性化修改 ,詳細見matplotlib官網。

my_dpi=150
plt.figure(figsize=(600/my_dpi, 600/my_dpi), dpi=my_dpi)
g=venn2(subsets = [{1,2,3},{1,2,4}], 
        set_labels = ('Label 1', 'Label 2'), 
        set_colors=("#098154","#c72e29"),
        alpha=0.6,
        normalize_to=1.0,
       )
g.get_label_by_id('10').set_fontfamily('Microsoft YaHei')#左圈中1的字體設置為微軟雅黑
g.get_label_by_id('10').set_fontsize(20)#1的大小設置為20
g.get_label_by_id('10').set_color('r')#1的顏色
g.get_label_by_id('10').set_rotation(45)#1的傾斜度

添加額外註釋 

my_dpi=150
plt.figure(figsize=(580/my_dpi, 580/my_dpi), dpi=my_dpi)#控制圖尺寸的同時,使圖高分辨率(高清)顯示
g=venn2(subsets = [{1,2,3},{1,2,4}], #繪圖數據集
        set_labels = ('Label 1', 'Label 2'), #設置組名
        set_colors=("#098154","#c72e29"),#設置圈的顏色,中間顏色不能修改
        alpha=0.6,#透明度
        normalize_to=1.0,#venn圖占據figure的比例,1.0為占滿
       )
 
plt.annotate('I like this green part!', 
             color='#098154',
             xy=g.get_label_by_id('10').get_position() - np.array([0, 0.05]), 
             xytext=(-80,40),
             ha='center', textcoords='offset points', 
             bbox=dict(boxstyle='round,pad=0.5', fc='#098154', alpha=0.6),#註釋文字底紋
             arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3,rad=0.5',color='#098154')#箭頭屬性設置
            )
 
 
plt.annotate('She like this red part!', 
             color='#c72e29',
             xy=g.get_label_by_id('01').get_position() + np.array([0, 0.05]), 
             xytext=(80,40),
             ha='center', textcoords='offset points', 
             bbox=dict(boxstyle='round,pad=0.5', fc='#c72e29', alpha=0.6),
             arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3,rad=0.5',color='#c72e29')
            )
 
plt.annotate('We both dislike this strange part!', 
             color='black',
             xy=g.get_label_by_id('11').get_position() + np.array([0, 0.05]), 
             xytext=(20,80),
             ha='center', textcoords='offset points', 
             bbox=dict(boxstyle='round,pad=0.5', fc='grey', alpha=0.6),
             arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3,rad=-0.5',color='black')
            )
 
plt.show()

多子圖繪制venn圖 

fig,axs=plt.subplots(1,3, figsize=(10,8),dpi=150)
g=venn2(subsets = [{1,2,3},{1,2,4}], 
        set_labels = ('Label 1', 'Label 2'), 
        set_colors=("#098154","#c72e29"),
        alpha=0.6,
        normalize_to=1.0,
        ax=axs[0],#該參數指定
       )
g=venn2(subsets = [{1,2,3,4,5,6},{1,2,4,5,6,7,8}], 
        set_labels = ('Label 3', 'Label 4'), 
        set_colors=("#098154","#c72e29"),
        alpha=0.6,
        normalize_to=1.0,
        ax=axs[1],
       )
g=venn2(subsets = [{0,1,2,3},{1,2,4}], 
        set_labels = ('Label 5', 'Label 6'), 
        set_colors=("#098154","#c72e29"),
        alpha=0.6,
        normalize_to=1.0,
        ax=axs[2],
       )
plt.show()

(2)3組數據venn圖

matplotlib_venn.venn3(subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None)

參數和venn2幾乎一樣,介紹幾個重要參數 

基本參數介紹

my_dpi=150
plt.figure(figsize=(600/my_dpi, 600/my_dpi), dpi=my_dpi)#控制圖尺寸的同時,使圖高分辨率(高清)顯示
g=venn3(subsets = [{1,2,3},{1,2,4},{2,6,7}], #傳入三組數據
        set_labels = ('Label 1', 'Label 2','Label 3'), #設置組名
        set_colors=("#01a2d9", "#31A354", "#c72e29"),#設置圈的顏色,中間顏色不能修改
        alpha=0.8,#透明度
        normalize_to=1.0,#venn圖占據figure的比例,1.0為占滿
       )
plt.show()

個性化設置圖中7部分每一部分

(100, 010, 110, 001, 101, 011, 111)分別代替每一小塊,那麼代替的是那一小塊瞭? 

my_dpi=150
plt.figure(figsize=(600/my_dpi, 600/my_dpi), dpi=my_dpi)
g=venn3(subsets = [{1,2,3},{1,2,4},{2,6,7}],
        set_labels = ('Label 1', 'Label 2','Label 3'),
        set_colors=("#01a2d9", "#31A354", "#c72e29"),
        alpha=0.8,
        normalize_to=1.0,
       )
 
for i in list('100, 010, 110, 001, 101, 011, 111'.split(', ')):
    g.get_label_by_id('%s'%i).set_text('%s'%i)#修改每個組分的文本
    
#然後就可以如同venn2中那樣個性化設置瞭
g.get_label_by_id('110').set_color('red')#1的顏色
g.get_patch_by_id('110').set_edgecolor('red')
 
plt.show()

2、pyvenn

同樣,該庫還是基於matplotlib.patches二次開發;

區別於上文,pyvenn支持2到6組數據;matplotlib_venn更加靈活多變。

pyvenn具有'venn2', 'venn3', 'venn4', 'venn5', 'venn6'五大主要函數,這裡主要介紹venn2,其它同理。

2組數據venn

venn.draw_annotate、venn.draw_text、venn.venn2中的fill()參數非常助於個性化設置。

venn2(labels, names=['A', 'B'], **options)   
import matplotlib.pyplot as plt
 
#添加pyvenn路徑
import sys
sys.path.append(r'path\pyvenn-master')
import venn
 
mycolor=[[0.10588235294117647, 0.6196078431372549, 0.4666666666666667,0.6],
         [0.9058823529411765, 0.1607843137254902, 0.5411764705882353, 0.6]]
 
labels = venn.get_labels([[1,2,3,4,5,6],[1,2,4,5,6,7,8]], fill=['number', 
                                                                'logic',#開啟每個組分代碼
                                                                'percent'#每個組分的百分比
                                                               ],
                        )
fig, ax = venn.venn2(labels,
                    names=list('AB'),
                    dpi=96,
                    colors=mycolor,#傳入RPGA色號,直接傳hex色號或者RGB會導致重疊部分被覆蓋
                    fontsize=15,#控制組名及中間數字大小
                   
                    
                    )
plt.style.use('seaborn-whitegrid')
ax.set_axis_on()#開啟坐標網格線
#ax.set_title('venn2')
 
 
 
# 提取plt.annotate部分參數
venn.draw_annotate(fig, ax, x=0.3, y=0.18, #箭頭的位置
                   textx=0.1, texty=0.05, #箭尾的位置
                   text='Aoligei!', color='r', #註釋文本屬性
                   arrowcolor='r',#箭頭的顏色等屬性
                  )
 
#添加文本
venn.draw_text(fig, ax, x=0.25, y=0.2, text='number:logic(percent)',
               fontsize=12, ha='center', va='center')

3組數據venn

labels = venn.get_labels([range(10), range(5, 15), range(3, 8)], fill=['number',
                                                                       'logic',
                                                                       'percent'
                                                                      ]
                        )
fig, ax = venn.venn3(labels, names=list('ABC'),dpi=96)
fig.show()

4組數據venn

labels = venn.get_labels([range(10), range(5, 15), range(3, 8), range(8, 17)], fill=['number', 
                                                                                     'logic',
                                                                                     'percent'                                                                                     
                                                                                    ])
fig, ax = venn.venn4(labels, names=list('ABCD'))
fig.show()

5組數據venn

labels = venn.get_labels([range(10), range(5, 15), range(3, 8), range(8, 17), range(10, 20)], fill=['number',
                                                                                                    'logic',
                                                                                                    'percent'
                                                                                                   ])
fig, ax = venn.venn5(labels, names=list('ABCDEF'))
fig.show()

6組數據venn

labels = venn.get_labels([range(10), range(5, 15), range(3, 8), range(8, 17), range(10, 20), range(13, 25)], fill=['number', 'logic','percent'])
fig, ax = venn.venn6(labels, names=list('ABCDEF'))
fig.show()

以上就是Python matplotlib可視化之繪制韋恩圖的詳細內容,更多關於Python matplotlib韋恩圖的資料請關註WalkonNet其它相關文章!

推薦閱讀: