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 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
|
"""
Venn diagram plotting routines.
Three-circle venn plotter.
Copyright 2012-2024, Konstantin Tretyakov.
http://kt.era.ee/
Licensed under MIT license.
"""
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, PathPatch
from matplotlib.path import Path
from matplotlib.colors import ColorConverter
from matplotlib.pyplot import gca
from matplotlib_venn._math import circle_circle_intersection, NUMERIC_TOLERANCE, Point2D
from matplotlib_venn._common import VennDiagram, prepare_venn_axes, mix_colors
from matplotlib_venn._region import VennRegion, VennCircleRegion, VennEmptyRegion
from matplotlib_venn.layout.api import VennLayout, VennLayoutAlgorithm
from matplotlib_venn.layout.venn3 import DefaultLayoutAlgorithm
Venn3SubsetSizes = Tuple[float, float, float, float, float, float, float]
def venn3_circles(
subsets: Union[Tuple[set, set, set], Dict[str, float], Venn3SubsetSizes],
normalize_to: Optional[float] = None,
alpha: float = 1.0,
color: Any = "black",
linestyle: str = "solid",
linewidth: str = 2.0,
ax: Optional[Axes] = None,
layout_algorithm: Optional[VennLayoutAlgorithm] = None,
**kwargs
) -> Tuple[Circle, Circle, Circle]:
"""
Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
Args:
subsets: Same as in `venn3`.
normalize_to: Same as in `venn3`.
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.venn3.DefaultLayoutAlgorithm(normalize_to).
**kwargs: passed as-is to matplotlib.patches.Circle.
Returns:
a list of three Circle patches plotted.
>>> plot = venn3_circles({'001': 10, '100': 20, '010': 21, '110': 13, '011': 14})
>>> plot = venn3_circles([set(['A','B','C']), set(['A','D','E','F']), set(['D','G','H'])])
"""
# 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_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.venn3.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 venn3(
subsets: Union[Tuple[set, set, set], Dict[str, float], Venn3SubsetSizes],
set_labels: Optional[Tuple[str, str, str]] = ("A", "B", "C"),
set_colors: Tuple[Any, Any, Any] = ("r", "g", "b"),
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,
) -> VennDiagram:
"""Plots a 3-set area-weighted Venn diagram.
Note: if some of the circles happen to have zero area, you will probably not get a nice picture.
Args:
subsets: one of the following:
- A tuple of three set objects.
- A dict, providing relative sizes of the seven diagram regions.
The regions are identified via three-letter binary codes ('100', '010', etc), hence a valid artgument could look like:
{'001': 10, '010': 20, '110':30, ...}. Unmentioned codes are considered to map to 0.
- A tuple with 7 numbers, denoting the sizes of the regions in the following order:
(100, 010, 110, 001, 101, 011, 111).
set_labels: An optional tuple of three strings - set labels. Set it to None to disable set labels.
set_colors: A tuple of three color specifications, specifying the base colors of the three circles.
The colors of circle intersections will be computed based on those.
normalize_to: Deprecated. Use normalize_to argument of matplotlib_venn.layout.venn3.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.venn3.DefaultLayoutAlgorithm().
Returns:
a `VennDiagram` object that keeps references to the layout information, ``Text`` and ``Patch`` objects used on the plot.
>>> 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_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.venn3.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: Venn3SubsetSizes,
set_labels: Optional[Tuple[str, str, str]] = ("A", "B", "C"),
set_colors: Tuple[Any, Any, Any] = ("r", "g", "b"),
alpha: float = 0.4,
ax: Optional[Axes] = None,
subset_label_formatter: Optional[Callable[[float], str]] = None,
) -> VennDiagram:
"""Given a VennLayout and the relevant rendering information, generates the diagram."""
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 = list(_compute_regions(layout.centers, layout.radii))
# 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(
layout.centers[i].asarray(),
layout.radii[i] + 0.001,
layout.centers[j].asarray(),
layout.radii[j] + 0.001,
)
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)
# 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], subset_label_formatter(s), va="center", ha="center")
if lbl is not None
else None
)
for (lbl, s) in zip(label_positions, subsets)
]
# Position set labels
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, Point2D], radii: Tuple[float, float, float]
) -> Tuple[
VennRegion, VennRegion, VennRegion, VennRegion, VennRegion, VennRegion, VennRegion
]:
"""
Given the three centers and radii of circles, returns the 7 regions, comprising the venn diagram, as VennRegion objects.
Regions are returned in order (Abc, aBc, ABc, abC, AbC, aBC, ABC)
>>> layout = DefaultLayoutAlgorithm()((1, 1, 1, 1, 1, 1, 1))
>>> regions = _compute_regions(layout.centers, layout.radii)
"""
A = VennCircleRegion(centers[0].asarray(), radii[0])
B = VennCircleRegion(centers[1].asarray(), radii[1])
C = VennCircleRegion(centers[2].asarray(), radii[2])
Ab, AB = A.subtract_and_intersect_circle(B.center, B.radius)
ABc, ABC = AB.subtract_and_intersect_circle(C.center, C.radius)
Abc, AbC = Ab.subtract_and_intersect_circle(C.center, C.radius)
aB, _ = B.subtract_and_intersect_circle(A.center, A.radius)
aBc, aBC = aB.subtract_and_intersect_circle(C.center, C.radius)
aC, _ = C.subtract_and_intersect_circle(A.center, A.radius)
abC, _ = aC.subtract_and_intersect_circle(B.center, B.radius)
return (Abc, aBc, ABc, abC, AbC, aBC, ABC)
def _compute_colors(
color_a: Any, color_b: Any, color_c: Any
) -> Tuple[
np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray
]:
"""
Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111).
>>> str(_compute_colors('r', 'g', 'b')).replace(' ', '')
'(array([1.,0.,0.]),...,array([0.4,0.2,0.4]))'
"""
ccv = ColorConverter()
base_colors = [np.array(ccv.to_rgb(c)) for c in [color_a, color_b, color_c]]
return (
base_colors[0],
base_colors[1],
mix_colors(base_colors[0], base_colors[1]),
base_colors[2],
mix_colors(base_colors[0], base_colors[2]),
mix_colors(base_colors[1], base_colors[2]),
mix_colors(base_colors[0], base_colors[1], base_colors[2]),
)
def _compute_subset_sizes(
a: Union[set, Counter], b: Union[set, Counter], c: Union[set, Counter]
) -> Venn3SubsetSizes:
"""
Given three set or Counter objects, computes the sizes of (a & ~b & ~c, ~a & b & ~c, a & b & ~c, ....),
as needed by the subsets parameter of venn3 and venn3_circles.
Returns the result as a tuple.
>>> _compute_subset_sizes(set([1,2,3]), set([2,3,4]), set([3,4,5,6]))
(1, 0, 1, 2, 0, 1, 1)
>>> _compute_subset_sizes(Counter([1,2,3]), Counter([2,3,4]), Counter([3,4,5,6]))
(1, 0, 1, 2, 0, 1, 1)
>>> _compute_subset_sizes(Counter([1,1,1]), Counter([1,1,1]), Counter([1,1,1,1]))
(0, 0, 0, 1, 0, 0, 3)
>>> _compute_subset_sizes(Counter([1,1,2,2,3,3]), Counter([2,2,3,3,4,4]), Counter([3,3,4,4,5,5,6,6]))
(2, 0, 2, 4, 0, 2, 2)
>>> _compute_subset_sizes(Counter([1,2,3]), Counter([2,2,3,3,4,4]), Counter([3,3,4,4,4,5,5,6]))
(1, 1, 1, 4, 0, 3, 1)
>>> _compute_subset_sizes(set([]), set([]), set([]))
(0, 0, 0, 0, 0, 0, 0)
>>> _compute_subset_sizes(set([1]), set([]), set([]))
(1, 0, 0, 0, 0, 0, 0)
>>> _compute_subset_sizes(set([]), set([1]), set([]))
(0, 1, 0, 0, 0, 0, 0)
>>> _compute_subset_sizes(set([]), set([]), set([1]))
(0, 0, 0, 1, 0, 0, 0)
>>> _compute_subset_sizes(Counter([]), Counter([]), Counter([1]))
(0, 0, 0, 1, 0, 0, 0)
>>> _compute_subset_sizes(set([1]), set([1]), set([1]))
(0, 0, 0, 0, 0, 0, 1)
>>> _compute_subset_sizes(set([1,3,5,7]), set([2,3,6,7]), set([4,5,6,7]))
(1, 1, 1, 1, 1, 1, 1)
>>> _compute_subset_sizes(Counter([1,3,5,7]), Counter([2,3,6,7]), Counter([4,5,6,7]))
(1, 1, 1, 1, 1, 1, 1)
>>> _compute_subset_sizes(Counter([1,3,5,7]), set([2,3,6,7]), set([4,5,6,7]))
Traceback (most recent call last):
...
ValueError: All arguments must be of the same type
"""
if not (type(a) == type(b) == type(c)):
raise ValueError("All 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 | c)
), # TODO: This is certainly not the most efficient way to compute.
set_size(b - (a | c)),
set_size((a & b) - c),
set_size(c - (a | b)),
set_size((a & c) - b),
set_size((b & c) - a),
set_size(a & b & c),
)
|