1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
|
"""
Venn diagram plotting routines.
Two-circle venn plotter.
Copyright 2012, Konstantin Tretyakov.
http://kt.era.ee/
Licensed under MIT license.
"""
# Make sure we don't try to do GUI stuff when running tests
import sys, os
if "py.test" in os.path.basename(sys.argv[0]): # (XXX: Ugly hack)
import matplotlib
matplotlib.use("Agg")
from typing import Any, Callable, Dict, Optional, Tuple, Union
import numpy as np
import warnings
from collections import Counter
from matplotlib.axes import Axes
from matplotlib.patches import Circle
from matplotlib.colors import ColorConverter
from matplotlib.pyplot import gca
from matplotlib_venn._math import Point2D
from matplotlib_venn._common import VennDiagram, prepare_venn_axes, mix_colors
from matplotlib_venn._region import VennRegion, VennCircleRegion
from matplotlib_venn.layout.api import VennLayout, VennLayoutAlgorithm
from matplotlib_venn.layout.venn2 import DefaultLayoutAlgorithm
Venn2SubsetSizes = Tuple[float, float, float]
def venn2_circles(
subsets: Union[Tuple[set, set], Dict[str, float], Venn2SubsetSizes],
normalize_to: Optional[float] = None,
alpha: float = 1.0,
color: Any = "black",
linestyle: str = "solid",
linewidth: float = 2.0,
ax: Axes = None,
layout_algorithm: Optional[VennLayoutAlgorithm] = None,
**kwargs
):
"""
Plots only the two circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
Args:
subsets: Same as in `venn2`.
normalize_to: Same as in `venn2`.
alpha: The alpha parameter of the circle patches.
color: The edgecolor of the circle patches (as understood by matplotlib).
linestyle: The linestyle of the circle patches.
linewidth: The line width of the circle patches.
ax: Axis to draw upon, defaults to gca().
layout_algorithm: The layout algorithm to be used. Defaults to matplotlib_venn.layout.venn2.DefaultLayoutAlgorithm(normalize_to).
**kwargs: passed as-is to matplotlib.patches.Circle.
Returns:
a list of two Circle patches plotted.
>>> c = venn2_circles((1, 2, 3))
>>> c = venn2_circles({'10': 1, '01': 2, '11': 3}) # Same effect
>>> c = venn2_circles([set([1,2,3,4]), set([2,3,4,5,6])]) # Also same effect
"""
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ["10", "01", "11"]]
elif len(subsets) == 2:
subsets = _compute_subset_sizes(*subsets)
if normalize_to is not None:
if layout_algorithm is None:
warnings.warn(
"normalize_to is deprecated. Please use layout_algorithm=matplotlib_venn.layout.venn2.DefaultLayoutAlgorithm(normalize_to) instead."
)
else:
raise ValueError(
"normalize_to is deprecated and may not be specified together with a custom layout algorithm."
)
if layout_algorithm is None:
layout_algorithm = DefaultLayoutAlgorithm(normalize_to=normalize_to or 1.0)
layout = layout_algorithm(subsets)
if ax is None:
ax = gca()
prepare_venn_axes(ax, layout.centers, layout.radii)
result = []
for c, r in zip(layout.centers, layout.radii):
circle = Circle(
c.asarray(),
r,
alpha=alpha,
edgecolor=color,
facecolor="none",
linestyle=linestyle,
linewidth=linewidth,
**kwargs
)
ax.add_patch(circle)
result.append(circle)
return tuple(result)
def venn2(
subsets: Union[Tuple[set, set], Dict[str, float], Venn2SubsetSizes],
set_labels: Optional[Tuple[str, str]] = ("A", "B"),
set_colors: Tuple[Any, Any] = ("r", "g"),
alpha: float = 0.4,
normalize_to: Optional[float] = None,
ax: Optional[Axes] = None,
subset_label_formatter: Optional[Callable[[float], str]] = None,
layout_algorithm: Optional[VennLayoutAlgorithm] = None,
):
"""Plots a 2-set area-weighted Venn diagram.
Args:
subsets: one of the following:
- A tuple of two set objects.
- A dict, providing relative sizes of the three diagram regions.
The regions are identified via two-letter binary codes ('10', '01', '11'), hence a valid artgument could look like:
{'01': 10, '11': 20}. Unmentioned codes are considered to map to 0.
- A tuple with 3 numbers, denoting the sizes of the regions in the following order:
(10, 01, 11).
set_labels: An optional tuple of two strings - set labels. Set it to None to disable set labels.
set_colors: A tuple of two color specifications, specifying the base colors of the two circles.
The colors of circle intersection will be computed based on those.
normalize_to: Deprecated. Use normalize_to argument of matplotlib_venn.layout.venn2.DefaultLayoutAlgorithm instead.
ax: The axes to plot upon. Defaults to gca().
subset_label_formatter: A function that converts numeric subset sizes to strings to be shown on the subset patches in the diagram.
Defaults to "str".
layout_algorithm: The layout algorithm to determine the scale and position of the three circles. Defaults to
matplotlib_venn.layout.venn2.DefaultLayoutAlgorithm().
Returns:
a `VennDiagram` object that keeps references to the layout information, ``Text`` and ``Patch`` objects used on the plot.
>>> from matplotlib_venn import *
>>> v = venn2(subsets={'10': 1, '01': 1, '11': 1}, set_labels = ('A', 'B'))
>>> c = venn2_circles(subsets=(1, 1, 1), linestyle='dashed')
>>> v.get_patch_by_id('10').set_alpha(1.0)
>>> v.get_patch_by_id('10').set_color('white')
>>> v.get_label_by_id('10').set_text('Unknown')
>>> v.get_label_by_id('A').set_text('Set A')
You can provide sets themselves rather than subset sizes:
>>> v = venn2(subsets=[set([1,2]), set([2,3,4,5])], set_labels = ('A', 'B'))
>>> c = venn2_circles(subsets=[set([1,2]), set([2,3,4,5])], linestyle='dashed')
>>> print("%0.2f" % (v.get_circle_radius(1)/v.get_circle_radius(0)))
1.41
"""
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ["10", "01", "11"]]
elif len(subsets) == 2:
subsets = _compute_subset_sizes(*subsets)
if normalize_to is not None:
if layout_algorithm is None:
warnings.warn(
"normalize_to is deprecated. Please use layout_algorithm=matplotlib_venn.layout.venn2.DefaultLayoutAlgorithm(normalize_to) instead."
)
else:
raise ValueError(
"normalize_to is deprecated and may not be specified together with a custom layout algorithm."
)
if layout_algorithm is None:
layout_algorithm = DefaultLayoutAlgorithm(normalize_to=normalize_to or 1.0)
layout = layout_algorithm(subsets, set_labels)
return _render_layout(
layout, subsets, set_labels, set_colors, alpha, ax, subset_label_formatter
)
def _render_layout(
layout: VennLayout,
subsets: Venn2SubsetSizes,
set_labels: Optional[Tuple[str, str]] = ("A", "B"),
set_colors: Tuple[Any, Any] = ("r", "g"),
alpha: float = 0.4,
ax: Optional[Axes] = None,
subset_label_formatter: Optional[Callable[[float], str]] = None,
) -> VennDiagram:
"""Renders the layout."""
if subset_label_formatter is None:
subset_label_formatter = str
if ax is None:
ax = gca()
prepare_venn_axes(ax, layout.centers, layout.radii)
colors = _compute_colors(*set_colors)
regions = _compute_regions(layout.centers, layout.radii)
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], subset_label_formatter(s), va="center", ha="center")
if lbl is not None
else None
)
for (lbl, s) in zip(label_positions, subsets)
]
if set_labels is not None:
labels = [
ax.text(lbl.position.x, lbl.position.y, txt, size="large", **lbl.kwargs)
for (lbl, txt) in zip(layout.set_labels_layout, set_labels)
]
else:
labels = None
return VennDiagram(patches, subset_labels, labels, layout.centers, layout.radii)
def _compute_regions(
centers: Tuple[Point2D, Point2D], radii: Tuple[float, float]
) -> Tuple[VennRegion, VennRegion, VennRegion]:
"""
Returns a triple of VennRegion objects, describing the three regions of the diagram, corresponding to sets
(Ab, aB, AB)
>>> layout = DefaultLayoutAlgorithm()((1, 1, 0.5))
>>> regions = _compute_regions(layout.centers, layout.radii)
"""
A = VennCircleRegion(centers[0].asarray(), radii[0])
B = VennCircleRegion(centers[1].asarray(), radii[1])
Ab, AB = A.subtract_and_intersect_circle(B.center, B.radius)
aB, _ = B.subtract_and_intersect_circle(A.center, A.radius)
return (Ab, aB, AB)
def _compute_colors(
color_a: Any, color_b: Any
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 3 elements, providing colors for regions (10, 01, 11).
>>> str(_compute_colors('r', 'g')).replace(' ', '')
'(array([1.,0.,0.]),array([0.,0.5,0.]),array([0.7,0.35,0.]))'
"""
ccv = ColorConverter()
base_colors = [np.array(ccv.to_rgb(c)) for c in [color_a, color_b]]
return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]))
def _compute_subset_sizes(
a: Union[set, Counter], b: Union[set, Counter]
) -> Tuple[float, float, float]:
"""
Given two set or Counter objects, computes the sizes of (a & ~b, b & ~a, a & b).
Returns the result as a tuple.
>>> _compute_subset_sizes(set([1,2,3,4]), set([2,3,4,5,6]))
(1, 2, 3)
>>> _compute_subset_sizes(Counter([1,2,3,4]), Counter([2,3,4,5,6]))
(1, 2, 3)
>>> _compute_subset_sizes(Counter([]), Counter([]))
(0, 0, 0)
>>> _compute_subset_sizes(set([]), set([]))
(0, 0, 0)
>>> _compute_subset_sizes(set([1]), set([]))
(1, 0, 0)
>>> _compute_subset_sizes(set([1]), set([1]))
(0, 0, 1)
>>> _compute_subset_sizes(Counter([1]), Counter([1]))
(0, 0, 1)
>>> _compute_subset_sizes(set([1,2]), set([1]))
(1, 0, 1)
>>> _compute_subset_sizes(Counter([1,1,2,2,2]), Counter([1,2,3,3]))
(3, 2, 2)
>>> _compute_subset_sizes(Counter([1,1,2]), Counter([1,2,2]))
(1, 1, 2)
>>> _compute_subset_sizes(Counter([1,1]), set([]))
Traceback (most recent call last):
...
ValueError: Both arguments must be of the same type
"""
if not (type(a) == type(b)):
raise ValueError("Both arguments must be of the same type")
set_size = (
len if type(a) != Counter else lambda x: sum(x.values())
) # We cannot use len to compute the cardinality of a Counter
return (set_size(a - b), set_size(b - a), set_size(a & b))
|