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
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.maps.connection_map
|
|
3
|
+
===========================
|
|
4
|
+
|
|
5
|
+
Connection map — lines or arcs drawn between geographic points to show
|
|
6
|
+
flows or relationships.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
import plotly.graph_objects as go
|
|
11
|
+
|
|
12
|
+
from plotify.base import BasePlot
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ConnectionMap(BasePlot):
|
|
16
|
+
"""
|
|
17
|
+
Connection map.
|
|
18
|
+
|
|
19
|
+
Pass two parallel lists/arrays of points: ``starts`` and ``ends``, each
|
|
20
|
+
containing ``(lon, lat)`` tuples. The Plotly backend renders proper
|
|
21
|
+
geodesic arcs via :class:`plotly.graph_objects.Scattergeo`; the Seaborn
|
|
22
|
+
backend draws straight line segments on a bare lat/lon plane.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
starts,
|
|
28
|
+
ends,
|
|
29
|
+
labels=None,
|
|
30
|
+
line_color="darkblue",
|
|
31
|
+
line_width=1.5,
|
|
32
|
+
scope="world",
|
|
33
|
+
title=None,
|
|
34
|
+
backend="seaborn",
|
|
35
|
+
**kwargs,
|
|
36
|
+
):
|
|
37
|
+
"""
|
|
38
|
+
This is used to create a connection map.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
starts : list[tuple[float, float]]
|
|
43
|
+
Starting ``(lon, lat)`` for each connection.
|
|
44
|
+
ends : list[tuple[float, float]]
|
|
45
|
+
Ending ``(lon, lat)`` for each connection.
|
|
46
|
+
labels : list[str], optional
|
|
47
|
+
Optional labels for each connection (Plotly hover text).
|
|
48
|
+
line_color : str, default="darkblue"
|
|
49
|
+
Line colour.
|
|
50
|
+
line_width : float, default=1.5
|
|
51
|
+
Line width.
|
|
52
|
+
scope : str, default="world"
|
|
53
|
+
Plotly geographic scope.
|
|
54
|
+
title : str, optional
|
|
55
|
+
Plot title.
|
|
56
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
57
|
+
Rendering backend.
|
|
58
|
+
**kwargs :
|
|
59
|
+
Forwarded to the underlying library.
|
|
60
|
+
|
|
61
|
+
Returns
|
|
62
|
+
-------
|
|
63
|
+
None
|
|
64
|
+
"""
|
|
65
|
+
if len(starts) != len(ends):
|
|
66
|
+
raise ValueError("`starts` and `ends` must have the same length.")
|
|
67
|
+
|
|
68
|
+
self.__starts = list(starts)
|
|
69
|
+
self.__ends = list(ends)
|
|
70
|
+
self.__labels = labels
|
|
71
|
+
self.__line_color = line_color
|
|
72
|
+
self.__line_width = line_width
|
|
73
|
+
self.__scope = scope
|
|
74
|
+
self.__kwargs = kwargs
|
|
75
|
+
|
|
76
|
+
super().__init__(backend=backend, title=title)
|
|
77
|
+
self._render()
|
|
78
|
+
|
|
79
|
+
def _plot_seaborn(self):
|
|
80
|
+
"""Draw straight line segments on a bare (lon, lat) plane."""
|
|
81
|
+
for (lon0, lat0), (lon1, lat1) in zip(self.__starts, self.__ends):
|
|
82
|
+
plt.plot(
|
|
83
|
+
[lon0, lon1],
|
|
84
|
+
[lat0, lat1],
|
|
85
|
+
color=self.__line_color,
|
|
86
|
+
linewidth=self.__line_width,
|
|
87
|
+
alpha=0.6,
|
|
88
|
+
)
|
|
89
|
+
# Endpoint markers help orient the reader.
|
|
90
|
+
plt.scatter([lon0, lon1], [lat0, lat1], color=self.__line_color, s=20)
|
|
91
|
+
|
|
92
|
+
plt.xlabel("lon")
|
|
93
|
+
plt.ylabel("lat")
|
|
94
|
+
if self._title:
|
|
95
|
+
plt.title(self._title)
|
|
96
|
+
|
|
97
|
+
def _plot_plotly(self):
|
|
98
|
+
"""Draw great-circle arcs with :class:`plotly.graph_objects.Scattergeo`."""
|
|
99
|
+
fig = go.Figure()
|
|
100
|
+
for i, ((lon0, lat0), (lon1, lat1)) in enumerate(
|
|
101
|
+
zip(self.__starts, self.__ends)
|
|
102
|
+
):
|
|
103
|
+
fig.add_trace(
|
|
104
|
+
go.Scattergeo(
|
|
105
|
+
lon=[lon0, lon1],
|
|
106
|
+
lat=[lat0, lat1],
|
|
107
|
+
mode="lines",
|
|
108
|
+
line=dict(width=self.__line_width, color=self.__line_color),
|
|
109
|
+
name=self.__labels[i] if self.__labels else None,
|
|
110
|
+
)
|
|
111
|
+
)
|
|
112
|
+
fig.update_layout(
|
|
113
|
+
geo=dict(scope=self.__scope),
|
|
114
|
+
title=self._title,
|
|
115
|
+
showlegend=bool(self.__labels),
|
|
116
|
+
)
|
|
117
|
+
self._fig = fig
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.maps.hexbin_map
|
|
3
|
+
=======================
|
|
4
|
+
|
|
5
|
+
Dual-backend hexagonal binning of geographic point data.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import plotly.figure_factory as ff
|
|
10
|
+
|
|
11
|
+
from plotify.base import BasePlot
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HexbinMap(BasePlot):
|
|
15
|
+
"""
|
|
16
|
+
Hexbin aggregation of (lat, lon) points.
|
|
17
|
+
|
|
18
|
+
Seaborn backend uses :func:`matplotlib.pyplot.hexbin`. Plotly backend
|
|
19
|
+
uses :func:`plotly.figure_factory.create_hexbin_mapbox` if Mapbox tiles
|
|
20
|
+
are available, falling back to a projected hexbin otherwise.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
df,
|
|
26
|
+
lat,
|
|
27
|
+
lon,
|
|
28
|
+
gridsize=25,
|
|
29
|
+
cmap="viridis",
|
|
30
|
+
title=None,
|
|
31
|
+
backend="seaborn",
|
|
32
|
+
**kwargs,
|
|
33
|
+
):
|
|
34
|
+
"""
|
|
35
|
+
This is used to create a hexbin map.
|
|
36
|
+
|
|
37
|
+
Parameters
|
|
38
|
+
----------
|
|
39
|
+
df : pandas.DataFrame
|
|
40
|
+
Input data.
|
|
41
|
+
lat, lon : str
|
|
42
|
+
Latitude / longitude column names.
|
|
43
|
+
gridsize : int, default=25
|
|
44
|
+
Number of hex bins along the x axis.
|
|
45
|
+
cmap : str, default="viridis"
|
|
46
|
+
Colormap.
|
|
47
|
+
title : str, optional
|
|
48
|
+
Plot title.
|
|
49
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
50
|
+
Rendering backend.
|
|
51
|
+
**kwargs :
|
|
52
|
+
Forwarded to the underlying library.
|
|
53
|
+
|
|
54
|
+
Returns
|
|
55
|
+
-------
|
|
56
|
+
None
|
|
57
|
+
"""
|
|
58
|
+
self.__df = df
|
|
59
|
+
self.__lat = lat
|
|
60
|
+
self.__lon = lon
|
|
61
|
+
self.__gridsize = gridsize
|
|
62
|
+
self.__cmap = cmap
|
|
63
|
+
self.__kwargs = kwargs
|
|
64
|
+
|
|
65
|
+
super().__init__(backend=backend, title=title)
|
|
66
|
+
self._render()
|
|
67
|
+
|
|
68
|
+
def _plot_seaborn(self):
|
|
69
|
+
"""Render using :func:`matplotlib.pyplot.hexbin`."""
|
|
70
|
+
plt.hexbin(
|
|
71
|
+
self.__df[self.__lon],
|
|
72
|
+
self.__df[self.__lat],
|
|
73
|
+
gridsize=self.__gridsize,
|
|
74
|
+
cmap=self.__cmap,
|
|
75
|
+
**self.__kwargs,
|
|
76
|
+
)
|
|
77
|
+
plt.colorbar(label="count")
|
|
78
|
+
plt.xlabel("lon")
|
|
79
|
+
plt.ylabel("lat")
|
|
80
|
+
if self._title:
|
|
81
|
+
plt.title(self._title)
|
|
82
|
+
|
|
83
|
+
def _plot_plotly(self):
|
|
84
|
+
"""Render using :func:`plotly.figure_factory.create_hexbin_mapbox`."""
|
|
85
|
+
fig = ff.create_hexbin_mapbox(
|
|
86
|
+
data_frame=self.__df,
|
|
87
|
+
lat=self.__lat,
|
|
88
|
+
lon=self.__lon,
|
|
89
|
+
nx_hexagon=self.__gridsize,
|
|
90
|
+
opacity=0.6,
|
|
91
|
+
color_continuous_scale=self.__cmap,
|
|
92
|
+
**self.__kwargs,
|
|
93
|
+
)
|
|
94
|
+
# Use OpenStreetMap tiles to avoid needing a Mapbox token.
|
|
95
|
+
fig.update_layout(mapbox_style="open-street-map", title=self._title)
|
|
96
|
+
self._fig = fig
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.network
|
|
3
|
+
===============
|
|
4
|
+
|
|
5
|
+
Network / graph plots: NetworkDiagram, ChordDiagram, SankeyDiagram,
|
|
6
|
+
ArcDiagram, HierarchicalEdgeBundling.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from plotify.network.arc_diagram import ArcDiagram
|
|
10
|
+
from plotify.network.chord_diagram import ChordDiagram
|
|
11
|
+
from plotify.network.hierarchical_edge_bundling import HierarchicalEdgeBundling
|
|
12
|
+
from plotify.network.network_diagram import NetworkDiagram
|
|
13
|
+
from plotify.network.sankey_diagram import SankeyDiagram
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"ArcDiagram",
|
|
17
|
+
"ChordDiagram",
|
|
18
|
+
"HierarchicalEdgeBundling",
|
|
19
|
+
"NetworkDiagram",
|
|
20
|
+
"SankeyDiagram",
|
|
21
|
+
]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.network.arc_diagram
|
|
3
|
+
===========================
|
|
4
|
+
|
|
5
|
+
Arc diagram — nodes arranged on a horizontal axis, edges drawn as semi-
|
|
6
|
+
circular arcs above (or below) the axis.
|
|
7
|
+
|
|
8
|
+
Plotly has no native arc-diagram primitive, so only the Seaborn/Matplotlib
|
|
9
|
+
backend is implemented.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import matplotlib.patches as patches
|
|
13
|
+
import matplotlib.pyplot as plt
|
|
14
|
+
import networkx as nx
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from plotify.base import BasePlot
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ArcDiagram(BasePlot):
|
|
21
|
+
"""
|
|
22
|
+
Arc diagram.
|
|
23
|
+
|
|
24
|
+
Accepts either a networkx graph or an edge list.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# Plotly has no built-in arc diagram.
|
|
28
|
+
SUPPORTED_BACKENDS = ("seaborn",)
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
graph=None,
|
|
33
|
+
edges=None,
|
|
34
|
+
node_order=None,
|
|
35
|
+
node_color="steelblue",
|
|
36
|
+
edge_color="gray",
|
|
37
|
+
title=None,
|
|
38
|
+
backend="seaborn",
|
|
39
|
+
**kwargs,
|
|
40
|
+
):
|
|
41
|
+
"""
|
|
42
|
+
This is used to create an arc diagram.
|
|
43
|
+
|
|
44
|
+
Parameters
|
|
45
|
+
----------
|
|
46
|
+
graph : networkx.Graph, optional
|
|
47
|
+
Pre-built graph. Mutually exclusive with ``edges``.
|
|
48
|
+
edges : list[tuple], optional
|
|
49
|
+
Edge list — each entry is ``(u, v)``.
|
|
50
|
+
node_order : list, optional
|
|
51
|
+
Explicit left-to-right ordering of nodes along the axis.
|
|
52
|
+
node_color : str, default="steelblue"
|
|
53
|
+
Node marker colour.
|
|
54
|
+
edge_color : str, default="gray"
|
|
55
|
+
Colour of the arcs.
|
|
56
|
+
title : str, optional
|
|
57
|
+
Plot title.
|
|
58
|
+
backend : {"seaborn"}
|
|
59
|
+
Only the Seaborn/Matplotlib backend is supported.
|
|
60
|
+
**kwargs :
|
|
61
|
+
Currently unused.
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
None
|
|
66
|
+
"""
|
|
67
|
+
if (graph is None) == (edges is None):
|
|
68
|
+
raise ValueError("Provide exactly one of `graph` or `edges`.")
|
|
69
|
+
|
|
70
|
+
if graph is None:
|
|
71
|
+
g = nx.Graph()
|
|
72
|
+
g.add_edges_from(edges)
|
|
73
|
+
graph = g
|
|
74
|
+
|
|
75
|
+
self.__graph = graph
|
|
76
|
+
self.__node_order = node_order or list(graph.nodes())
|
|
77
|
+
self.__node_color = node_color
|
|
78
|
+
self.__edge_color = edge_color
|
|
79
|
+
self.__kwargs = kwargs
|
|
80
|
+
|
|
81
|
+
super().__init__(backend=backend, title=title)
|
|
82
|
+
self._render()
|
|
83
|
+
|
|
84
|
+
def _plot_seaborn(self):
|
|
85
|
+
"""Draw nodes along y=0 and edges as semicircular arcs above."""
|
|
86
|
+
order = self.__node_order
|
|
87
|
+
positions = {node: i for i, node in enumerate(order)}
|
|
88
|
+
|
|
89
|
+
fig, ax = plt.subplots()
|
|
90
|
+
# Arcs are drawn as matplotlib Arc patches — one per edge.
|
|
91
|
+
max_distance = 1
|
|
92
|
+
for u, v in self.__graph.edges():
|
|
93
|
+
x_u = positions[u]
|
|
94
|
+
x_v = positions[v]
|
|
95
|
+
centre = (x_u + x_v) / 2
|
|
96
|
+
width = abs(x_v - x_u)
|
|
97
|
+
max_distance = max(max_distance, width)
|
|
98
|
+
arc = patches.Arc(
|
|
99
|
+
(centre, 0),
|
|
100
|
+
width=width,
|
|
101
|
+
height=width,
|
|
102
|
+
angle=0,
|
|
103
|
+
theta1=0,
|
|
104
|
+
theta2=180,
|
|
105
|
+
color=self.__edge_color,
|
|
106
|
+
linewidth=1.5,
|
|
107
|
+
)
|
|
108
|
+
ax.add_patch(arc)
|
|
109
|
+
|
|
110
|
+
# Plot the node markers on the horizontal axis.
|
|
111
|
+
xs = [positions[n] for n in order]
|
|
112
|
+
ax.scatter(xs, [0] * len(xs), color=self.__node_color, s=80, zorder=3)
|
|
113
|
+
for node, x in positions.items():
|
|
114
|
+
ax.text(x, -0.05 * max_distance, str(node), ha="center", va="top", fontsize=9)
|
|
115
|
+
|
|
116
|
+
ax.set_xlim(-1, len(order))
|
|
117
|
+
ax.set_ylim(-0.1 * max_distance, max_distance / 2 + 1)
|
|
118
|
+
ax.set_aspect("equal")
|
|
119
|
+
ax.axis("off")
|
|
120
|
+
if self._title:
|
|
121
|
+
ax.set_title(self._title)
|
|
122
|
+
|
|
123
|
+
# Silence unused-import warning: numpy is used implicitly by matplotlib.
|
|
124
|
+
_ = np.asarray([])
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.network.chord_diagram
|
|
3
|
+
=============================
|
|
4
|
+
|
|
5
|
+
Chord diagram — nodes arranged on a circle, with chords representing flows
|
|
6
|
+
between them. Plotly has no native chord primitive, so only the
|
|
7
|
+
Seaborn/Matplotlib backend is implemented.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import matplotlib.patches as patches
|
|
11
|
+
import matplotlib.pyplot as plt
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from plotify.base import BasePlot
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ChordDiagram(BasePlot):
|
|
18
|
+
"""
|
|
19
|
+
Chord diagram from a symmetric connection matrix.
|
|
20
|
+
|
|
21
|
+
The input is a square (N × N) matrix where cell ``(i, j)`` is the
|
|
22
|
+
strength of the connection between node ``i`` and node ``j``.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
# Plotly has no native chord primitive.
|
|
26
|
+
SUPPORTED_BACKENDS = ("seaborn",)
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
matrix,
|
|
31
|
+
labels=None,
|
|
32
|
+
colors=None,
|
|
33
|
+
title=None,
|
|
34
|
+
backend="seaborn",
|
|
35
|
+
**kwargs,
|
|
36
|
+
):
|
|
37
|
+
"""
|
|
38
|
+
This is used to create a chord diagram.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
matrix : 2D array-like
|
|
43
|
+
Square symmetric matrix of connection strengths.
|
|
44
|
+
labels : list[str], optional
|
|
45
|
+
Node labels. Defaults to ``"0", "1", ...``.
|
|
46
|
+
colors : list[str], optional
|
|
47
|
+
Colour per node.
|
|
48
|
+
title : str, optional
|
|
49
|
+
Plot title.
|
|
50
|
+
backend : {"seaborn"}
|
|
51
|
+
Only the Seaborn/Matplotlib backend is supported.
|
|
52
|
+
**kwargs :
|
|
53
|
+
Currently unused — accepted for forward compatibility.
|
|
54
|
+
|
|
55
|
+
Returns
|
|
56
|
+
-------
|
|
57
|
+
None
|
|
58
|
+
"""
|
|
59
|
+
mat = np.asarray(matrix, dtype=float)
|
|
60
|
+
if mat.ndim != 2 or mat.shape[0] != mat.shape[1]:
|
|
61
|
+
raise ValueError("`matrix` must be a square 2D array.")
|
|
62
|
+
|
|
63
|
+
self.__matrix = mat
|
|
64
|
+
self.__labels = labels or [str(i) for i in range(mat.shape[0])]
|
|
65
|
+
self.__colors = colors
|
|
66
|
+
self.__kwargs = kwargs
|
|
67
|
+
|
|
68
|
+
super().__init__(backend=backend, title=title)
|
|
69
|
+
self._render()
|
|
70
|
+
|
|
71
|
+
def _plot_seaborn(self):
|
|
72
|
+
"""Draw nodes on a circle and chords as quadratic Bezier curves."""
|
|
73
|
+
n = self.__matrix.shape[0]
|
|
74
|
+
# Evenly spaced node angles around the unit circle.
|
|
75
|
+
angles = np.linspace(0, 2 * np.pi, n, endpoint=False)
|
|
76
|
+
positions = np.column_stack([np.cos(angles), np.sin(angles)])
|
|
77
|
+
|
|
78
|
+
cmap = plt.get_cmap("tab10")
|
|
79
|
+
node_colors = self.__colors or [cmap(i % 10) for i in range(n)]
|
|
80
|
+
|
|
81
|
+
fig, ax = plt.subplots()
|
|
82
|
+
ax.set_aspect("equal")
|
|
83
|
+
ax.set_xlim(-1.3, 1.3)
|
|
84
|
+
ax.set_ylim(-1.3, 1.3)
|
|
85
|
+
ax.axis("off")
|
|
86
|
+
|
|
87
|
+
# Chords: for each unordered pair (i<j) with non-zero strength, draw
|
|
88
|
+
# a Bezier curve whose control point is the origin.
|
|
89
|
+
max_strength = self.__matrix.max() or 1.0
|
|
90
|
+
for i in range(n):
|
|
91
|
+
for j in range(i + 1, n):
|
|
92
|
+
strength = self.__matrix[i, j]
|
|
93
|
+
if strength == 0:
|
|
94
|
+
continue
|
|
95
|
+
path_data = [
|
|
96
|
+
(patches.Path.MOVETO, positions[i]),
|
|
97
|
+
(patches.Path.CURVE3, (0, 0)),
|
|
98
|
+
(patches.Path.CURVE3, positions[j]),
|
|
99
|
+
]
|
|
100
|
+
codes, verts = zip(*path_data)
|
|
101
|
+
path = patches.Path(verts, codes)
|
|
102
|
+
patch = patches.PathPatch(
|
|
103
|
+
path,
|
|
104
|
+
facecolor="none",
|
|
105
|
+
edgecolor=node_colors[i],
|
|
106
|
+
linewidth=1 + 4 * strength / max_strength,
|
|
107
|
+
alpha=0.6,
|
|
108
|
+
)
|
|
109
|
+
ax.add_patch(patch)
|
|
110
|
+
|
|
111
|
+
# Node markers + labels.
|
|
112
|
+
for i, (x, y) in enumerate(positions):
|
|
113
|
+
ax.plot(x, y, "o", color=node_colors[i], markersize=10)
|
|
114
|
+
# Offset label outwards from the node.
|
|
115
|
+
lx, ly = 1.12 * x, 1.12 * y
|
|
116
|
+
ax.text(lx, ly, self.__labels[i], ha="center", va="center", fontsize=9)
|
|
117
|
+
|
|
118
|
+
if self._title:
|
|
119
|
+
ax.set_title(self._title)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.network.hierarchical_edge_bundling
|
|
3
|
+
==========================================
|
|
4
|
+
|
|
5
|
+
Hierarchical edge bundling — leaves arranged on the circumference of a
|
|
6
|
+
circle in hierarchical order; connections between leaves are drawn as
|
|
7
|
+
curves that bundle together along the implied tree structure.
|
|
8
|
+
|
|
9
|
+
Plotly has no native hierarchical-edge-bundling primitive, so only the
|
|
10
|
+
Seaborn/Matplotlib backend is implemented. The tree is unused in this
|
|
11
|
+
simplified version beyond the leaf ordering.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import matplotlib.patches as patches
|
|
15
|
+
import matplotlib.pyplot as plt
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from plotify.base import BasePlot
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class HierarchicalEdgeBundling(BasePlot):
|
|
22
|
+
"""
|
|
23
|
+
Simplified hierarchical edge bundling.
|
|
24
|
+
|
|
25
|
+
Leaves (nodes) are placed on the unit circle. Each connection is drawn
|
|
26
|
+
as a cubic Bezier curve with control points biased towards the circle
|
|
27
|
+
centre, producing the characteristic "bundled" look.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
# Plotly has no native equivalent.
|
|
31
|
+
SUPPORTED_BACKENDS = ("seaborn",)
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
leaves,
|
|
36
|
+
connections,
|
|
37
|
+
bundle_strength=0.75,
|
|
38
|
+
leaf_color="steelblue",
|
|
39
|
+
edge_color="gray",
|
|
40
|
+
title=None,
|
|
41
|
+
backend="seaborn",
|
|
42
|
+
**kwargs,
|
|
43
|
+
):
|
|
44
|
+
"""
|
|
45
|
+
This is used to create a hierarchical edge bundling plot.
|
|
46
|
+
|
|
47
|
+
Parameters
|
|
48
|
+
----------
|
|
49
|
+
leaves : list
|
|
50
|
+
Leaf labels in circular order.
|
|
51
|
+
connections : list[tuple]
|
|
52
|
+
List of ``(source_label, target_label)`` pairs.
|
|
53
|
+
bundle_strength : float, default=0.75
|
|
54
|
+
How strongly to pull Bezier control points towards the centre.
|
|
55
|
+
``0`` = straight lines; ``1`` = full bundling through the origin.
|
|
56
|
+
leaf_color : str, default="steelblue"
|
|
57
|
+
Leaf marker colour.
|
|
58
|
+
edge_color : str, default="gray"
|
|
59
|
+
Curve colour.
|
|
60
|
+
title : str, optional
|
|
61
|
+
Plot title.
|
|
62
|
+
backend : {"seaborn"}
|
|
63
|
+
Only the Seaborn/Matplotlib backend is supported.
|
|
64
|
+
**kwargs :
|
|
65
|
+
Currently unused.
|
|
66
|
+
|
|
67
|
+
Returns
|
|
68
|
+
-------
|
|
69
|
+
None
|
|
70
|
+
"""
|
|
71
|
+
if not 0 <= bundle_strength <= 1:
|
|
72
|
+
raise ValueError("`bundle_strength` must be in [0, 1].")
|
|
73
|
+
|
|
74
|
+
self.__leaves = list(leaves)
|
|
75
|
+
self.__connections = list(connections)
|
|
76
|
+
self.__bundle_strength = bundle_strength
|
|
77
|
+
self.__leaf_color = leaf_color
|
|
78
|
+
self.__edge_color = edge_color
|
|
79
|
+
self.__kwargs = kwargs
|
|
80
|
+
|
|
81
|
+
super().__init__(backend=backend, title=title)
|
|
82
|
+
self._render()
|
|
83
|
+
|
|
84
|
+
def _plot_seaborn(self):
|
|
85
|
+
"""Place leaves on a circle, draw bundled Bezier edges between them."""
|
|
86
|
+
n = len(self.__leaves)
|
|
87
|
+
# Even angular spacing around the circle.
|
|
88
|
+
angles = np.linspace(0, 2 * np.pi, n, endpoint=False)
|
|
89
|
+
positions = {
|
|
90
|
+
leaf: np.array([np.cos(a), np.sin(a)])
|
|
91
|
+
for leaf, a in zip(self.__leaves, angles)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
fig, ax = plt.subplots()
|
|
95
|
+
ax.set_aspect("equal")
|
|
96
|
+
ax.set_xlim(-1.3, 1.3)
|
|
97
|
+
ax.set_ylim(-1.3, 1.3)
|
|
98
|
+
ax.axis("off")
|
|
99
|
+
|
|
100
|
+
# Each edge is a cubic Bezier whose two control points are the
|
|
101
|
+
# source and target positions scaled toward the origin.
|
|
102
|
+
s = 1 - self.__bundle_strength
|
|
103
|
+
for u, v in self.__connections:
|
|
104
|
+
if u not in positions or v not in positions:
|
|
105
|
+
continue
|
|
106
|
+
p0 = positions[u]
|
|
107
|
+
p3 = positions[v]
|
|
108
|
+
p1 = p0 * s
|
|
109
|
+
p2 = p3 * s
|
|
110
|
+
verts = [tuple(p0), tuple(p1), tuple(p2), tuple(p3)]
|
|
111
|
+
codes = [
|
|
112
|
+
patches.Path.MOVETO,
|
|
113
|
+
patches.Path.CURVE4,
|
|
114
|
+
patches.Path.CURVE4,
|
|
115
|
+
patches.Path.CURVE4,
|
|
116
|
+
]
|
|
117
|
+
path = patches.Path(verts, codes)
|
|
118
|
+
ax.add_patch(
|
|
119
|
+
patches.PathPatch(
|
|
120
|
+
path,
|
|
121
|
+
facecolor="none",
|
|
122
|
+
edgecolor=self.__edge_color,
|
|
123
|
+
linewidth=0.8,
|
|
124
|
+
alpha=0.6,
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# Leaf markers and labels placed just outside the circle.
|
|
129
|
+
for leaf, pos in positions.items():
|
|
130
|
+
ax.plot(pos[0], pos[1], "o", color=self.__leaf_color, markersize=6)
|
|
131
|
+
ax.text(
|
|
132
|
+
pos[0] * 1.1,
|
|
133
|
+
pos[1] * 1.1,
|
|
134
|
+
str(leaf),
|
|
135
|
+
ha="center",
|
|
136
|
+
va="center",
|
|
137
|
+
fontsize=8,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
if self._title:
|
|
141
|
+
ax.set_title(self._title)
|