plotify-charts 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plotify/__init__.py +116 -0
- plotify/_inference.py +144 -0
- plotify/auto.py +360 -0
- plotify/base.py +224 -0
- plotify/categorical/__init__.py +37 -0
- plotify/categorical/bar_plot.py +121 -0
- plotify/categorical/circular_packing.py +107 -0
- plotify/categorical/dendrogram.py +113 -0
- plotify/categorical/doughnut_chart.py +109 -0
- plotify/categorical/lollipop_chart.py +168 -0
- plotify/categorical/parallel_coordinates.py +94 -0
- plotify/categorical/pie_chart.py +101 -0
- plotify/categorical/radar_chart.py +116 -0
- plotify/categorical/sunburst_diagram.py +117 -0
- plotify/categorical/treemap.py +121 -0
- plotify/categorical/venn_diagram.py +92 -0
- plotify/categorical/word_cloud.py +104 -0
- plotify/maps/__init__.py +21 -0
- plotify/maps/bubble_map.py +114 -0
- plotify/maps/cartogram.py +126 -0
- plotify/maps/choropleth_map.py +108 -0
- plotify/maps/connection_map.py +117 -0
- plotify/maps/hexbin_map.py +96 -0
- plotify/network/__init__.py +21 -0
- plotify/network/arc_diagram.py +124 -0
- plotify/network/chord_diagram.py +119 -0
- plotify/network/hierarchical_edge_bundling.py +141 -0
- plotify/network/network_diagram.py +167 -0
- plotify/network/sankey_diagram.py +258 -0
- plotify/num_cat/__init__.py +19 -0
- plotify/num_cat/box_plot_by_group.py +110 -0
- plotify/num_cat/grouped_bar_plot.py +110 -0
- plotify/num_cat/grouped_scatter.py +105 -0
- plotify/num_cat/stacked_bar_plot.py +117 -0
- plotify/numerical/__init__.py +21 -0
- plotify/numerical/boxplot.py +157 -0
- plotify/numerical/connected_scatter_plot.py +120 -0
- plotify/numerical/density_plot.py +184 -0
- plotify/numerical/scatter_plot.py +140 -0
- plotify/numerical/violin_plot.py +141 -0
- plotify/theme.py +297 -0
- plotify/timeseries/__init__.py +13 -0
- plotify/timeseries/area_chart.py +89 -0
- plotify/timeseries/line_chart.py +110 -0
- plotify/timeseries/stacked_area_chart.py +133 -0
- plotify/timeseries/stream_graph.py +116 -0
- plotify_charts-0.1.0.dist-info/LICENSE +21 -0
- plotify_charts-0.1.0.dist-info/METADATA +226 -0
- plotify_charts-0.1.0.dist-info/RECORD +50 -0
- plotify_charts-0.1.0.dist-info/WHEEL +4 -0
plotify/base.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.base
|
|
3
|
+
============
|
|
4
|
+
|
|
5
|
+
Base class that every Plotify plot inherits from.
|
|
6
|
+
|
|
7
|
+
The class provides:
|
|
8
|
+
|
|
9
|
+
* A **dual backend** dispatch — every concrete plot class ships two render
|
|
10
|
+
implementations, ``_plot_seaborn`` (Matplotlib / Seaborn) and
|
|
11
|
+
``_plot_plotly`` (Plotly). The backend is chosen at construction time.
|
|
12
|
+
* A common ``save_plot`` helper that knows how to write both matplotlib
|
|
13
|
+
figures (``.png`` / ``.svg`` / ``.pdf`` via ``matplotlib.figure.Figure``)
|
|
14
|
+
and Plotly figures (static via ``kaleido`` or interactive ``.html``).
|
|
15
|
+
* A consistent lifecycle that preserves the "plot on instantiation" behaviour
|
|
16
|
+
of the original :mod:`numerical` module, so user code such as
|
|
17
|
+
``Boxplot(df, x="cat", y="val")`` continues to render immediately.
|
|
18
|
+
|
|
19
|
+
A subclass only needs to implement :py:meth:`_plot_seaborn` and
|
|
20
|
+
:py:meth:`_plot_plotly` (either one may raise :class:`NotImplementedError` if
|
|
21
|
+
that backend has no sensible equivalent — e.g. Venn diagrams in Plotly).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
|
|
26
|
+
import matplotlib.pyplot as plt
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BasePlot:
|
|
30
|
+
"""
|
|
31
|
+
Abstract base class for every Plotify plot.
|
|
32
|
+
|
|
33
|
+
Parameters
|
|
34
|
+
----------
|
|
35
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
36
|
+
Which rendering engine to use. ``"seaborn"`` uses Seaborn/Matplotlib
|
|
37
|
+
and produces static images; ``"plotly"`` produces interactive figures.
|
|
38
|
+
title : str, optional
|
|
39
|
+
Optional title applied after rendering.
|
|
40
|
+
|
|
41
|
+
Attributes
|
|
42
|
+
----------
|
|
43
|
+
SUPPORTED_BACKENDS : tuple[str, ...]
|
|
44
|
+
Backends this class can render on. Subclasses may override this to
|
|
45
|
+
advertise that they only support a subset (e.g. Word Cloud supports
|
|
46
|
+
only ``"seaborn"``).
|
|
47
|
+
_fig : matplotlib.figure.Figure | plotly.graph_objects.Figure | None
|
|
48
|
+
The rendered figure, populated by :py:meth:`_render`.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
# The set of backends this *class* can render on. Subclasses with
|
|
52
|
+
# single-backend support should override this so the base validator
|
|
53
|
+
# raises a clear message (rather than letting the render method fail).
|
|
54
|
+
SUPPORTED_BACKENDS = ("seaborn", "plotly")
|
|
55
|
+
|
|
56
|
+
def __init__(self, backend="seaborn", title=None):
|
|
57
|
+
"""
|
|
58
|
+
Initialise the base plot.
|
|
59
|
+
|
|
60
|
+
Parameters
|
|
61
|
+
----------
|
|
62
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
63
|
+
The rendering backend for this instance.
|
|
64
|
+
title : str, optional
|
|
65
|
+
Plot title. Applied uniformly across both backends.
|
|
66
|
+
|
|
67
|
+
Raises
|
|
68
|
+
------
|
|
69
|
+
ValueError
|
|
70
|
+
If ``backend`` is not one of ``self.SUPPORTED_BACKENDS``.
|
|
71
|
+
"""
|
|
72
|
+
# Validate early — easier to debug than a KeyError deep in a render path.
|
|
73
|
+
if backend not in self.SUPPORTED_BACKENDS:
|
|
74
|
+
raise ValueError(
|
|
75
|
+
f"Backend {backend!r} not supported by {type(self).__name__}. "
|
|
76
|
+
f"Supported: {self.SUPPORTED_BACKENDS}"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
self._backend = backend
|
|
80
|
+
self._title = title
|
|
81
|
+
self._fig = None # populated by _render() in the concrete subclass
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def fig(self):
|
|
85
|
+
"""The underlying figure object.
|
|
86
|
+
|
|
87
|
+
Returns the active :class:`matplotlib.figure.Figure` (Seaborn
|
|
88
|
+
backend) or :class:`plotly.graph_objects.Figure` (Plotly backend).
|
|
89
|
+
Useful in notebooks: ``MyPlot(...).fig`` displays the plot inline,
|
|
90
|
+
and Plotly figures expose their full ``.show()`` / ``.update_*``
|
|
91
|
+
APIs.
|
|
92
|
+
"""
|
|
93
|
+
return self._fig
|
|
94
|
+
|
|
95
|
+
# ------------------------------------------------------------------ #
|
|
96
|
+
# Render dispatch
|
|
97
|
+
# ------------------------------------------------------------------ #
|
|
98
|
+
def _render(self):
|
|
99
|
+
"""
|
|
100
|
+
Dispatch to the correct backend render method.
|
|
101
|
+
|
|
102
|
+
Subclasses should call this at the end of their ``__init__`` after
|
|
103
|
+
all plot-specific attributes have been stored.
|
|
104
|
+
"""
|
|
105
|
+
# Apply the active Plotify theme to the chosen backend's global
|
|
106
|
+
# state before rendering. Imported lazily to avoid the import cycle
|
|
107
|
+
# between base.py and the concrete plot modules that theme.py
|
|
108
|
+
# touches when ``apply_smart_ticks_to_current_axes`` runs.
|
|
109
|
+
from plotify import theme as _theme
|
|
110
|
+
|
|
111
|
+
_theme.apply_current(self._backend)
|
|
112
|
+
|
|
113
|
+
# Single place that routes to one of the two private render methods.
|
|
114
|
+
# Each subclass implements them; if a backend is unsupported it can
|
|
115
|
+
# either raise NotImplementedError inside that method or narrow
|
|
116
|
+
# ``SUPPORTED_BACKENDS`` so the ValueError is raised in ``__init__``.
|
|
117
|
+
if self._backend == "seaborn":
|
|
118
|
+
# Open a fresh matplotlib figure so we never inherit stale axis
|
|
119
|
+
# state (e.g., a categorical converter set by a prior plot)
|
|
120
|
+
# from whatever was last drawn onto pyplot's global state.
|
|
121
|
+
plt.figure()
|
|
122
|
+
self._plot_seaborn()
|
|
123
|
+
# Capture whichever figure ended up active. Seaborn helpers
|
|
124
|
+
# like ``lmplot`` / ``catplot`` create their own FacetGrid, so
|
|
125
|
+
# we cannot assume our ``plt.figure()`` above is what got drawn.
|
|
126
|
+
self._fig = plt.gcf()
|
|
127
|
+
# Apply tick formatters that rcParams cannot express directly
|
|
128
|
+
# (1.2K / 3.4M / etc.). Safe on date / category axes — the
|
|
129
|
+
# helper skips formatters that aren't ScalarFormatter.
|
|
130
|
+
_theme.apply_smart_ticks_to_current_axes()
|
|
131
|
+
else:
|
|
132
|
+
self._plot_plotly()
|
|
133
|
+
|
|
134
|
+
def _plot_seaborn(self):
|
|
135
|
+
"""Render using Seaborn / Matplotlib. Must be implemented by subclasses."""
|
|
136
|
+
raise NotImplementedError(
|
|
137
|
+
f"{type(self).__name__} does not implement a Seaborn/Matplotlib backend."
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
def _plot_plotly(self):
|
|
141
|
+
"""Render using Plotly. Must be implemented by subclasses."""
|
|
142
|
+
raise NotImplementedError(
|
|
143
|
+
f"{type(self).__name__} does not implement a Plotly backend."
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
# ------------------------------------------------------------------ #
|
|
147
|
+
# Saving
|
|
148
|
+
# ------------------------------------------------------------------ #
|
|
149
|
+
def save_plot(self, file_name, folder=None, size=(10, 6)):
|
|
150
|
+
"""
|
|
151
|
+
Save the rendered figure to disk.
|
|
152
|
+
|
|
153
|
+
Parameters
|
|
154
|
+
----------
|
|
155
|
+
file_name : str
|
|
156
|
+
The target file name. Extension determines the output format:
|
|
157
|
+
|
|
158
|
+
* Seaborn backend: ``.png``, ``.jpg``, ``.pdf``, ``.svg`` — anything
|
|
159
|
+
:func:`matplotlib.pyplot.savefig` accepts.
|
|
160
|
+
* Plotly backend: ``.html`` writes an interactive figure,
|
|
161
|
+
anything else is treated as a static image and rendered via
|
|
162
|
+
:mod:`kaleido`.
|
|
163
|
+
folder : str, optional
|
|
164
|
+
Directory to place the file in. Created if missing.
|
|
165
|
+
size : tuple[float, float], default=(10, 6)
|
|
166
|
+
Figure size in inches (Seaborn) or the ``(width, height)`` pair
|
|
167
|
+
passed to Plotly's ``write_image``/``update_layout`` — inches are
|
|
168
|
+
converted to pixels at 100 DPI.
|
|
169
|
+
|
|
170
|
+
Returns
|
|
171
|
+
-------
|
|
172
|
+
str
|
|
173
|
+
The absolute or relative path the file was written to.
|
|
174
|
+
"""
|
|
175
|
+
# Resolve final path, creating the folder if needed.
|
|
176
|
+
if folder:
|
|
177
|
+
if not os.path.exists(folder):
|
|
178
|
+
os.makedirs(folder)
|
|
179
|
+
file_name = os.path.join(folder, file_name)
|
|
180
|
+
|
|
181
|
+
# Dispatch based on backend so callers do not need to care which one
|
|
182
|
+
# produced the figure.
|
|
183
|
+
if self._backend == "seaborn":
|
|
184
|
+
self._save_seaborn(file_name, size)
|
|
185
|
+
else:
|
|
186
|
+
self._save_plotly(file_name, size)
|
|
187
|
+
|
|
188
|
+
return file_name
|
|
189
|
+
|
|
190
|
+
def _save_seaborn(self, file_name, size):
|
|
191
|
+
"""Persist the current Matplotlib state to ``file_name``.
|
|
192
|
+
|
|
193
|
+
The concrete subclass already called ``self._plot_seaborn()`` during
|
|
194
|
+
``__init__`` which drew onto the current pyplot state. Here we simply
|
|
195
|
+
resize the active figure and save it, then close it to keep notebook
|
|
196
|
+
environments tidy.
|
|
197
|
+
"""
|
|
198
|
+
# Re-render onto a fresh figure so that saving does not depend on
|
|
199
|
+
# whatever state the caller's notebook left behind.
|
|
200
|
+
fig = plt.figure(figsize=size)
|
|
201
|
+
self._plot_seaborn()
|
|
202
|
+
plt.savefig(file_name)
|
|
203
|
+
plt.close(fig) # prevent figure from popping up in notebooks
|
|
204
|
+
plt.ion() # restore interactive mode for any subsequent plots
|
|
205
|
+
|
|
206
|
+
def _save_plotly(self, file_name, size):
|
|
207
|
+
"""Persist the stored Plotly figure to ``file_name``."""
|
|
208
|
+
if self._fig is None:
|
|
209
|
+
# Defensive: concrete subclasses should always populate _fig.
|
|
210
|
+
raise RuntimeError(
|
|
211
|
+
"Plotly figure has not been constructed; did _plot_plotly() run?"
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
# Convert the (width, height) inch tuple to pixels at 100 DPI so that
|
|
215
|
+
# a size of (10, 6) maps to 1000×600 — consistent with matplotlib defaults.
|
|
216
|
+
width_px = int(size[0] * 100)
|
|
217
|
+
height_px = int(size[1] * 100)
|
|
218
|
+
|
|
219
|
+
# ``.html`` -> interactive; anything else -> static image via kaleido.
|
|
220
|
+
if file_name.lower().endswith(".html"):
|
|
221
|
+
self._fig.update_layout(width=width_px, height=height_px)
|
|
222
|
+
self._fig.write_html(file_name)
|
|
223
|
+
else:
|
|
224
|
+
self._fig.write_image(file_name, width=width_px, height=height_px)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.categorical
|
|
3
|
+
===================
|
|
4
|
+
|
|
5
|
+
Plots for categorical data: BarPlot, LollipopChart, RadarChart (alias
|
|
6
|
+
SpiderChart), ParallelCoordinates, WordCloudPlot, PieChart, DoughnutChart,
|
|
7
|
+
Treemap, CircularPacking, SunburstDiagram, VennDiagram, Dendrogram.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from plotify.categorical.bar_plot import BarPlot
|
|
11
|
+
from plotify.categorical.circular_packing import CircularPacking
|
|
12
|
+
from plotify.categorical.dendrogram import Dendrogram
|
|
13
|
+
from plotify.categorical.doughnut_chart import DoughnutChart
|
|
14
|
+
from plotify.categorical.lollipop_chart import LollipopChart
|
|
15
|
+
from plotify.categorical.parallel_coordinates import ParallelCoordinates
|
|
16
|
+
from plotify.categorical.pie_chart import PieChart
|
|
17
|
+
from plotify.categorical.radar_chart import RadarChart, SpiderChart
|
|
18
|
+
from plotify.categorical.sunburst_diagram import SunburstDiagram
|
|
19
|
+
from plotify.categorical.treemap import Treemap
|
|
20
|
+
from plotify.categorical.venn_diagram import VennDiagram
|
|
21
|
+
from plotify.categorical.word_cloud import WordCloudPlot
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"BarPlot",
|
|
25
|
+
"CircularPacking",
|
|
26
|
+
"Dendrogram",
|
|
27
|
+
"DoughnutChart",
|
|
28
|
+
"LollipopChart",
|
|
29
|
+
"ParallelCoordinates",
|
|
30
|
+
"PieChart",
|
|
31
|
+
"RadarChart",
|
|
32
|
+
"SpiderChart",
|
|
33
|
+
"SunburstDiagram",
|
|
34
|
+
"Treemap",
|
|
35
|
+
"VennDiagram",
|
|
36
|
+
"WordCloudPlot",
|
|
37
|
+
]
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.categorical.bar_plot
|
|
3
|
+
============================
|
|
4
|
+
|
|
5
|
+
Dual-backend bar plot wrapping :func:`seaborn.barplot` and
|
|
6
|
+
:func:`plotly.express.bar`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
import plotly.express as px
|
|
11
|
+
import seaborn as sns
|
|
12
|
+
|
|
13
|
+
from plotify.base import BasePlot
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BarPlot(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Represent categorical entities with bars whose length encodes a numeric value.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
df,
|
|
24
|
+
x=None,
|
|
25
|
+
y=None,
|
|
26
|
+
hue=None,
|
|
27
|
+
order=None,
|
|
28
|
+
hue_order=None,
|
|
29
|
+
orient=None,
|
|
30
|
+
color=None,
|
|
31
|
+
palette=None,
|
|
32
|
+
estimator="mean",
|
|
33
|
+
ci=95,
|
|
34
|
+
title=None,
|
|
35
|
+
backend="seaborn",
|
|
36
|
+
**kwargs,
|
|
37
|
+
):
|
|
38
|
+
"""
|
|
39
|
+
This is used to create a bar plot.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
df : pandas.DataFrame
|
|
44
|
+
Input data.
|
|
45
|
+
x, y : str, optional
|
|
46
|
+
Column names for the categorical axis and numeric axis.
|
|
47
|
+
hue : str, optional
|
|
48
|
+
Column name for colour grouping.
|
|
49
|
+
order, hue_order : list, optional
|
|
50
|
+
Category ordering.
|
|
51
|
+
orient : {"v", "h"}, optional
|
|
52
|
+
Orientation (Seaborn only).
|
|
53
|
+
color : str, optional
|
|
54
|
+
A single colour override (Seaborn only).
|
|
55
|
+
palette : str or list, optional
|
|
56
|
+
Colour palette.
|
|
57
|
+
estimator : str or callable, default="mean"
|
|
58
|
+
Aggregation applied when multiple observations share a category
|
|
59
|
+
(Seaborn only).
|
|
60
|
+
ci : float, default=95
|
|
61
|
+
Confidence interval size for the error bars (Seaborn only).
|
|
62
|
+
title : str, optional
|
|
63
|
+
Plot title.
|
|
64
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
65
|
+
Rendering backend.
|
|
66
|
+
**kwargs :
|
|
67
|
+
Forwarded to the underlying library function.
|
|
68
|
+
|
|
69
|
+
Returns
|
|
70
|
+
-------
|
|
71
|
+
None
|
|
72
|
+
"""
|
|
73
|
+
self.__df = df
|
|
74
|
+
self.__x = x
|
|
75
|
+
self.__y = y
|
|
76
|
+
self.__hue = hue
|
|
77
|
+
self.__order = order
|
|
78
|
+
self.__hue_order = hue_order
|
|
79
|
+
self.__orient = orient
|
|
80
|
+
self.__color = color
|
|
81
|
+
self.__palette = palette
|
|
82
|
+
self.__estimator = estimator
|
|
83
|
+
self.__ci = ci
|
|
84
|
+
self.__kwargs = kwargs
|
|
85
|
+
|
|
86
|
+
super().__init__(backend=backend, title=title)
|
|
87
|
+
self._render()
|
|
88
|
+
|
|
89
|
+
def _plot_seaborn(self):
|
|
90
|
+
"""Render using :func:`seaborn.barplot`."""
|
|
91
|
+
sns.barplot(
|
|
92
|
+
data=self.__df,
|
|
93
|
+
x=self.__x,
|
|
94
|
+
y=self.__y,
|
|
95
|
+
hue=self.__hue,
|
|
96
|
+
order=self.__order,
|
|
97
|
+
hue_order=self.__hue_order,
|
|
98
|
+
orient=self.__orient,
|
|
99
|
+
color=self.__color,
|
|
100
|
+
palette=self.__palette,
|
|
101
|
+
estimator=self.__estimator,
|
|
102
|
+
**self.__kwargs,
|
|
103
|
+
)
|
|
104
|
+
if self._title:
|
|
105
|
+
plt.title(self._title)
|
|
106
|
+
|
|
107
|
+
def _plot_plotly(self):
|
|
108
|
+
"""Render using :func:`plotly.express.bar`."""
|
|
109
|
+
fig = px.bar(
|
|
110
|
+
self.__df,
|
|
111
|
+
x=self.__x,
|
|
112
|
+
y=self.__y,
|
|
113
|
+
color=self.__hue,
|
|
114
|
+
orientation=(self.__orient if self.__orient in ("h", "v") else None),
|
|
115
|
+
category_orders=(
|
|
116
|
+
{self.__x: self.__order} if self.__order and self.__x else None
|
|
117
|
+
),
|
|
118
|
+
title=self._title,
|
|
119
|
+
**self.__kwargs,
|
|
120
|
+
)
|
|
121
|
+
self._fig = fig
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.categorical.circular_packing
|
|
3
|
+
====================================
|
|
4
|
+
|
|
5
|
+
Circular packing — hierarchical data displayed as circles inside circles.
|
|
6
|
+
Plotly has no built-in equivalent, so only the Seaborn/Matplotlib backend
|
|
7
|
+
is implemented.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import circlify
|
|
11
|
+
import matplotlib.pyplot as plt
|
|
12
|
+
|
|
13
|
+
from plotify.base import BasePlot
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CircularPacking(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Circular packing chart.
|
|
19
|
+
|
|
20
|
+
Uses the :mod:`circlify` library to compute a nested-circle layout and
|
|
21
|
+
Matplotlib to render it.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
# Plotly has no circular-packing primitive; advertise this at class level.
|
|
25
|
+
SUPPORTED_BACKENDS = ("seaborn",)
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
df,
|
|
30
|
+
labels,
|
|
31
|
+
values,
|
|
32
|
+
show_enclosure=False,
|
|
33
|
+
cmap="tab20",
|
|
34
|
+
title=None,
|
|
35
|
+
backend="seaborn",
|
|
36
|
+
**kwargs,
|
|
37
|
+
):
|
|
38
|
+
"""
|
|
39
|
+
This is used to create a circular packing chart.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
df : pandas.DataFrame
|
|
44
|
+
Input data — one row per leaf circle.
|
|
45
|
+
labels : str
|
|
46
|
+
Column with circle labels.
|
|
47
|
+
values : str
|
|
48
|
+
Column with numeric sizes.
|
|
49
|
+
show_enclosure : bool, default=False
|
|
50
|
+
Whether to draw the outer bounding circle.
|
|
51
|
+
cmap : str, default="tab20"
|
|
52
|
+
Matplotlib colormap used for per-circle colours.
|
|
53
|
+
title : str, optional
|
|
54
|
+
Plot title.
|
|
55
|
+
backend : {"seaborn"}
|
|
56
|
+
Only the Seaborn/Matplotlib backend is supported.
|
|
57
|
+
**kwargs :
|
|
58
|
+
Forwarded to :func:`circlify.circlify`.
|
|
59
|
+
|
|
60
|
+
Returns
|
|
61
|
+
-------
|
|
62
|
+
None
|
|
63
|
+
"""
|
|
64
|
+
self.__df = df
|
|
65
|
+
self.__labels = labels
|
|
66
|
+
self.__values = values
|
|
67
|
+
self.__show_enclosure = show_enclosure
|
|
68
|
+
self.__cmap = cmap
|
|
69
|
+
self.__kwargs = kwargs
|
|
70
|
+
|
|
71
|
+
super().__init__(backend=backend, title=title)
|
|
72
|
+
self._render()
|
|
73
|
+
|
|
74
|
+
def _plot_seaborn(self):
|
|
75
|
+
"""Compute the packing layout and draw it."""
|
|
76
|
+
# circlify packs in descending size order, so sort for stable output.
|
|
77
|
+
sorted_df = self.__df.sort_values(self.__values, ascending=False)
|
|
78
|
+
|
|
79
|
+
circles = circlify.circlify(
|
|
80
|
+
sorted_df[self.__values].tolist(),
|
|
81
|
+
show_enclosure=self.__show_enclosure,
|
|
82
|
+
target_enclosure=circlify.Circle(x=0, y=0, r=1),
|
|
83
|
+
**self.__kwargs,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
fig, ax = plt.subplots()
|
|
87
|
+
ax.set_aspect("equal")
|
|
88
|
+
# circlify returns coordinates in [-1, 1] — pad slightly for labels.
|
|
89
|
+
ax.set_xlim(-1.1, 1.1)
|
|
90
|
+
ax.set_ylim(-1.1, 1.1)
|
|
91
|
+
ax.axis("off")
|
|
92
|
+
|
|
93
|
+
cmap = plt.get_cmap(self.__cmap)
|
|
94
|
+
labels = sorted_df[self.__labels].tolist()
|
|
95
|
+
for i, circle in enumerate(circles):
|
|
96
|
+
x, y, r = circle.x, circle.y, circle.r
|
|
97
|
+
ax.add_patch(
|
|
98
|
+
plt.Circle(
|
|
99
|
+
(x, y), r, alpha=0.6, edgecolor="black", facecolor=cmap(i % 20)
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
# Only label circles big enough to read.
|
|
103
|
+
if r > 0.05:
|
|
104
|
+
ax.text(x, y, labels[i], ha="center", va="center", fontsize=8)
|
|
105
|
+
|
|
106
|
+
if self._title:
|
|
107
|
+
ax.set_title(self._title)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.categorical.dendrogram
|
|
3
|
+
==============================
|
|
4
|
+
|
|
5
|
+
Dendrogram — tree diagram produced by hierarchical clustering.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import numpy as np
|
|
10
|
+
import plotly.figure_factory as ff
|
|
11
|
+
from scipy.cluster import hierarchy
|
|
12
|
+
|
|
13
|
+
from plotify.base import BasePlot
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Dendrogram(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Dendrogram from a numeric matrix.
|
|
19
|
+
|
|
20
|
+
Seaborn backend uses :func:`scipy.cluster.hierarchy.linkage` + dendrogram;
|
|
21
|
+
Plotly backend uses :func:`plotly.figure_factory.create_dendrogram`.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
df,
|
|
27
|
+
labels=None,
|
|
28
|
+
method="single",
|
|
29
|
+
metric="euclidean",
|
|
30
|
+
orientation="top",
|
|
31
|
+
title=None,
|
|
32
|
+
backend="seaborn",
|
|
33
|
+
**kwargs,
|
|
34
|
+
):
|
|
35
|
+
"""
|
|
36
|
+
This is used to create a dendrogram.
|
|
37
|
+
|
|
38
|
+
Parameters
|
|
39
|
+
----------
|
|
40
|
+
df : pandas.DataFrame or array-like
|
|
41
|
+
Observation matrix — rows are observations, columns are features.
|
|
42
|
+
labels : list[str], optional
|
|
43
|
+
Leaf labels, one per row.
|
|
44
|
+
method : str, default="single"
|
|
45
|
+
Linkage method (see :func:`scipy.cluster.hierarchy.linkage`).
|
|
46
|
+
metric : str, default="euclidean"
|
|
47
|
+
Pair-wise distance metric.
|
|
48
|
+
orientation : {"top", "bottom", "left", "right"}, default="top"
|
|
49
|
+
Dendrogram orientation.
|
|
50
|
+
title : str, optional
|
|
51
|
+
Plot title.
|
|
52
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
53
|
+
Rendering backend.
|
|
54
|
+
**kwargs :
|
|
55
|
+
Forwarded to the underlying library.
|
|
56
|
+
|
|
57
|
+
Returns
|
|
58
|
+
-------
|
|
59
|
+
None
|
|
60
|
+
"""
|
|
61
|
+
self.__df = df
|
|
62
|
+
self.__labels = labels
|
|
63
|
+
self.__method = method
|
|
64
|
+
self.__metric = metric
|
|
65
|
+
self.__orientation = orientation
|
|
66
|
+
self.__kwargs = kwargs
|
|
67
|
+
|
|
68
|
+
super().__init__(backend=backend, title=title)
|
|
69
|
+
self._render()
|
|
70
|
+
|
|
71
|
+
def _plot_seaborn(self):
|
|
72
|
+
"""Render using scipy + matplotlib."""
|
|
73
|
+
data = np.asarray(self.__df)
|
|
74
|
+
# linkage expects the condensed distance or the raw matrix.
|
|
75
|
+
Z = hierarchy.linkage(data, method=self.__method, metric=self.__metric)
|
|
76
|
+
hierarchy.dendrogram(
|
|
77
|
+
Z,
|
|
78
|
+
labels=self.__labels,
|
|
79
|
+
orientation=self.__orientation,
|
|
80
|
+
**self.__kwargs,
|
|
81
|
+
)
|
|
82
|
+
if self._title:
|
|
83
|
+
plt.title(self._title)
|
|
84
|
+
|
|
85
|
+
# Plotly's ff.create_dendrogram inverts scipy's orientation convention:
|
|
86
|
+
# passing orientation="top" makes the tree hang downward with negative
|
|
87
|
+
# y values, the opposite of scipy. We swap orientations here so the
|
|
88
|
+
# ``orientation`` argument has the same meaning across both backends —
|
|
89
|
+
# i.e., the scipy convention (root at the named side, leaves opposite).
|
|
90
|
+
_PLOTLY_ORIENTATION_FLIP = {
|
|
91
|
+
"top": "bottom",
|
|
92
|
+
"bottom": "top",
|
|
93
|
+
"left": "right",
|
|
94
|
+
"right": "left",
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
def _plot_plotly(self):
|
|
98
|
+
"""Render using :func:`plotly.figure_factory.create_dendrogram`."""
|
|
99
|
+
data = np.asarray(self.__df)
|
|
100
|
+
plotly_orientation = self._PLOTLY_ORIENTATION_FLIP.get(
|
|
101
|
+
self.__orientation, self.__orientation
|
|
102
|
+
)
|
|
103
|
+
fig = ff.create_dendrogram(
|
|
104
|
+
data,
|
|
105
|
+
labels=self.__labels,
|
|
106
|
+
linkagefun=lambda x: hierarchy.linkage(
|
|
107
|
+
data, method=self.__method, metric=self.__metric
|
|
108
|
+
),
|
|
109
|
+
orientation=plotly_orientation,
|
|
110
|
+
)
|
|
111
|
+
if self._title:
|
|
112
|
+
fig.update_layout(title=self._title)
|
|
113
|
+
self._fig = fig
|