Esempio n. 1
0
def venn3_unweighted(subsets,
                     set_labels=('A', 'B', 'C'),
                     set_colors=('r', 'g', 'b'),
                     alpha=0.4,
                     normalize_to=1.0,
                     subset_areas=(1, 1, 1, 1, 1, 1, 1),
                     ax=None):
    '''
    The version of venn3 without area-weighting.
    It is implemented as a wrapper around venn3. Namely, venn3 is invoked as usual, but with all subset areas
    set to 1. The subset labels are then replaced in the resulting diagram with the provided subset sizes.
    
    The parameters are all the same as that of venn2.
    In addition there is a subset_areas parameter, which specifies the actual subset areas.
    (it is (1, 1, 1, 1, 1, 1, 1) by default. You are free to change it, within reason).
    '''
    v = venn3(subset_areas, set_labels, set_colors, alpha, normalize_to, ax)
    # Now rename the labels
    subset_ids = ['100', '010', '110', '001', '101', '011', '111']
    if isinstance(subsets, dict):
        subsets = [subsets.get(t, 0) for t in subset_ids]
    elif len(subsets) == 3:
        subsets = compute_venn3_subsets(*subsets)
    for n, id in enumerate(subset_ids):
        lbl = v.get_label_by_id(id)
        if lbl is not None:
            lbl.set_text(str(subsets[n]))
    return v
def getVenn3plot(sets, labels, title, path_to_img):

    v = venn3(subsets=sets, set_labels=labels)
    print(_venn3.compute_venn3_subsets(sets[0], sets[1], sets[2]))
    # v.get_patch_by_id('11').set_color('purple')
    # v.get_patch_by_id('01').set_color('blue')

    plt.title(title)

    plt.savefig(path_to_img, bbox_inches='tight')
    plt.show()
Esempio n. 3
0
def venn3_unweighted(subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1, 1, 1, 1, 1), ax=None):
    '''
    The version of venn3 without area-weighting.
    It is implemented as a wrapper around venn3. Namely, venn3 is invoked as usual, but with all subset areas
    set to 1. The subset labels are then replaced in the resulting diagram with the provided subset sizes.
    
    The parameters are all the same as that of venn2.
    In addition there is a subset_areas parameter, which specifies the actual subset areas.
    (it is (1, 1, 1, 1, 1, 1, 1) by default. You are free to change it, within reason).
    '''
    v = venn3(subset_areas, set_labels, set_colors, alpha, normalize_to, ax)
    # Now rename the labels
    subset_ids = ['100', '010', '110', '001', '101', '011', '111']
    if isinstance(subsets, dict):
        subsets = [subsets.get(t, 0) for t in subset_ids]
    elif len(subsets) == 3:
        subsets = compute_venn3_subsets(*subsets)
    for n, id in enumerate(subset_ids):
        lbl = v.get_label_by_id(id)
        if lbl is not None:
            lbl.set_text(str(subsets[n]))
    return v
Esempio n. 4
0
def make_vens(sample_dict, samples, title='', save=None, normalized=False):
    # sample_dict: {sample: values_to_use}
    # samples: list of sample to use for venn. Is a subset of sample_dict.keys()
    # title: title for plot
    # save: folder to save plot in, or None
    # normalized: boolean normalize total to 100

    if len(samples) not in [2,3]:
        print("2 or 3 samples required")
        return None
    pylab.figure(figsize=(6,6))
    ax = pylab.axes()
    p,l = zip(*[(dta,sample) for sample,dta in sample_dict.items() if sample in samples])
    n_str = ""
    if normalized:
        n_str = "_norm"
        p = np.array(_venn3.compute_venn3_subsets(*p)) if len(samples) == 3 else np.array(_venn2.compute_venn2_subsets(*p))
        p = (100*p/sum(p)).round()
    venn(p,l, ax=ax)
    pylab.title(title)
    if save:
        file_name = ','.join(samples) + "_" + title + n_str + ".pdf"
        pylab.savefig(os.path.join(save,file_name), bbox_inches='tight')
Esempio n. 5
0
def venn3(subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, ax=None):
    '''Plots a 3-set area-weighted Venn diagram.
    The subsets parameter can be one of the following:
     - A list (or a tuple), containing three set objects.
     - A dict, providing sizes of seven diagram regions.
       The regions are identified via three-letter binary codes ('100', '010', etc), hence a valid set could look like:
       {'001': 10, '010': 20, '110':30, ...}. Unmentioned codes are considered to map to 0.
     - A list (or a tuple) with 7 numbers, denoting the sizes of the regions in the following order:
       (100, 010, 110, 001, 101, 011, 111).

    ``set_labels`` parameter is a list of three strings - set labels. Set it to None to disable set labels.
    The ``set_colors`` parameter should be a list of three elements, specifying the "base colors" of the three circles.
    The colors of circle intersections will be computed based on those.

    The ``normalize_to`` parameter specifies the total (on-axes) area of the circles to be drawn. Sometimes tuning it (together
    with the overall fiture size) may be useful to fit the text labels better.
    The return value is a ``VennDiagram`` object, that keeps references to the ``Text`` and ``Patch`` objects used on the plot
    and lets you know the centers and radii of the circles, if you need it.

    The ``ax`` parameter specifies the axes on which the plot will be drawn (None means current axes).

    Note: if some of the circles happen to have zero area, you will probably not get a nice picture.

    >>> import matplotlib # (The first two lines prevent the doctest from falling when TCL not installed. Not really necessary in most cases)
    >>> matplotlib.use('Agg')
    >>> from matplotlib_venn import *
    >>> v = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C'))
    >>> c = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed')
    >>> v.get_patch_by_id('100').set_alpha(1.0)
    >>> v.get_patch_by_id('100').set_color('white')
    >>> v.get_label_by_id('100').set_text('Unknown')
    >>> v.get_label_by_id('C').set_text('Set C')

    You can provide sets themselves rather than subset sizes:
    >>> v = venn3(subsets=[set([1,2]), set([2,3,4,5]), set([4,5,6,7,8,9,10,11])])
    >>> print("%0.2f %0.2f %0.2f" % (v.get_circle_radius(0), v.get_circle_radius(1)/v.get_circle_radius(0), v.get_circle_radius(2)/v.get_circle_radius(0)))
    0.24 1.41 2.00
    >>> c = venn3_circles(subsets=[set([1,2]), set([2,3,4,5]), set([4,5,6,7,8,9,10,11])])
    '''
    # Prepare parameters
    if isinstance(subsets, dict):
        subsets = [subsets.get(t, 0) for t in ['100', '010', '110', '001', '101', '011', '111']]
    elif len(subsets) == 3:
        subsets = compute_venn3_subsets(*subsets)

    areas = compute_venn3_areas(subsets, normalize_to)
    centers, radii = solve_venn3_circles(areas)
    regions = compute_venn3_regions(centers, radii)
    colors = compute_venn3_colors(set_colors)

    # Remove regions that are too small from the diagram
    MIN_REGION_SIZE = 1e-4
    for i in range(len(regions)):
        if regions[i].size() < MIN_REGION_SIZE and subsets[i] == 0:
            regions[i] = VennEmptyRegion()

    # There is a rare case (Issue #12) when the middle region is visually empty
    # (the positioning of the circles does not let them intersect), yet the corresponding value is not 0.
    # we address it separately here by positioning the label of that empty region in a custom way
    if isinstance(regions[6], VennEmptyRegion) and subsets[6] > 0:
        intersections = [circle_circle_intersection(centers[i], radii[i], centers[j], radii[j]) for (i, j) in
                         [(0, 1), (1, 2), (2, 0)]]
        middle_pos = np.mean([i[0] for i in intersections], 0)
        regions[6] = VennEmptyRegion(middle_pos)

    if ax is None:
        ax = gca()
    prepare_venn_axes(ax, centers, radii)

    # Create and add patches and text
    patches = [r.make_patch() for r in regions]
    for (p, c) in zip(patches, colors):
        if p is not None:
            p.set_facecolor(c)
            p.set_edgecolor('none')
            p.set_alpha(alpha)
            ax.add_patch(p)
    label_positions = [r.label_position() for r in regions]
    subset_labels = [ax.text(lbl[0], lbl[1], str(s), va='center', ha='center') if lbl is not None else None for (lbl, s)
                     in zip(label_positions, subsets)]

    # Position labels
    if set_labels is not None:
        # There are two situations, when set C is not on the same line with sets A and B, and when the three are on the same line.
        if abs(centers[2][1] - centers[0][1]) > tol:
            # Three circles NOT on the same line
            label_positions = [centers[0] + np.array([-radii[0] / 2, radii[0]]),
                               centers[1] + np.array([radii[1] / 2, radii[1]]),
                               centers[2] + np.array([0.0, -radii[2] * 1.1])]
            labels = [ax.text(pos[0], pos[1], txt, size='large') for (pos, txt) in zip(label_positions, set_labels)]
            labels[0].set_horizontalalignment('right')
            labels[1].set_horizontalalignment('left')
            labels[2].set_verticalalignment('top')
            labels[2].set_horizontalalignment('center')
        else:
            padding = np.mean([r * 0.1 for r in radii])
            # Three circles on the same line
            label_positions = [centers[0] + np.array([0.0, - radii[0] - padding]),
                               centers[1] + np.array([0.0, - radii[1] - padding]),
                               centers[2] + np.array([0.0, - radii[2] - padding])]
            labels = [ax.text(pos[0], pos[1], txt, size='large', ha='center', va='top') for (pos, txt) in
                      zip(label_positions, set_labels)]
    else:
        labels = None
    return VennDiagram(patches, subset_labels, labels, centers, radii)
Esempio n. 6
0
0.22 0.71 2.36


B,A,C
[54    {6] 38 [74} 583]

54+6 =      60  B
6+38+74 =   118 A
74+583 =    657 C
Just B = 54
Just A = 38
Just C = 583
"""

subsets = compute_venn3_subsets(*[A, B, C])
areas = compute_venn3_areas(subsets, normalize_to)  = (0.15629139072847681, 0.079470198675496692, 0.87019867549668872, 0.0079470198675496689, 0.0, 0.098013245033112581, 0.0)
_areas = [Fraction(a).limit_denominator() for a in areas] #[Fraction(118, 755), Fraction(12, 151), Fraction(657, 755), Fraction(6, 755), Fraction(0, 1),
# Fraction(74, 755), Fraction(0, 1)]
c, r = solve_venn3_circles(compute_venn3_areas((38, 54, 6, 583, 74, 0, 0)))
np.round(r, 3) = array([0.223, 0.159, 0.526])
centers, radii = solve_venn3_circles(areas)
regions = compute_venn3_regions(centers, radii)
colors = compute_venn3_colors(set_colors)

#cc = tools.mpl_to_plotly(c.get_figure())

def subsets(a,b,c): return (len(a - (b.union(c))),  # TODO: This is certainly not the most efficient way to compute.
                       len(b - (a.union(c))),
                       len(a.intersection(b) - c),
                       len(c - (a.union(b))),