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,167 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.network.network_diagram
|
|
3
|
+
===============================
|
|
4
|
+
|
|
5
|
+
Dual-backend generic network / graph visualization using :mod:`networkx`
|
|
6
|
+
for the layout.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
import networkx as nx
|
|
11
|
+
import plotly.graph_objects as go
|
|
12
|
+
|
|
13
|
+
from plotify.base import BasePlot
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NetworkDiagram(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Generic node-link network diagram.
|
|
19
|
+
|
|
20
|
+
Accepts either a :class:`networkx.Graph` directly or an edge list
|
|
21
|
+
(list of ``(u, v)`` or ``(u, v, weight)`` tuples).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
graph=None,
|
|
27
|
+
edges=None,
|
|
28
|
+
layout="spring",
|
|
29
|
+
node_color="steelblue",
|
|
30
|
+
node_size=300,
|
|
31
|
+
edge_color="gray",
|
|
32
|
+
with_labels=True,
|
|
33
|
+
title=None,
|
|
34
|
+
backend="seaborn",
|
|
35
|
+
**kwargs,
|
|
36
|
+
):
|
|
37
|
+
"""
|
|
38
|
+
This is used to create a network diagram.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
graph : networkx.Graph, optional
|
|
43
|
+
Pre-built graph. Mutually exclusive with ``edges``.
|
|
44
|
+
edges : list[tuple], optional
|
|
45
|
+
Edge list. Each entry is ``(u, v)`` or ``(u, v, weight)``.
|
|
46
|
+
layout : {"spring", "circular", "kamada_kawai", "random", "shell"}, default="spring"
|
|
47
|
+
Node-placement algorithm.
|
|
48
|
+
node_color : str, default="steelblue"
|
|
49
|
+
Node colour.
|
|
50
|
+
node_size : int, default=300
|
|
51
|
+
Node size (matplotlib units).
|
|
52
|
+
edge_color : str, default="gray"
|
|
53
|
+
Edge colour.
|
|
54
|
+
with_labels : bool, default=True
|
|
55
|
+
Draw node labels.
|
|
56
|
+
title : str, optional
|
|
57
|
+
Plot title.
|
|
58
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
59
|
+
Rendering backend.
|
|
60
|
+
**kwargs :
|
|
61
|
+
Forwarded to :func:`networkx.draw` (Seaborn backend only).
|
|
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
|
+
# Normalise to a networkx graph so both render paths are the same.
|
|
71
|
+
if graph is None:
|
|
72
|
+
g = nx.Graph()
|
|
73
|
+
for edge in edges:
|
|
74
|
+
if len(edge) == 2:
|
|
75
|
+
g.add_edge(edge[0], edge[1])
|
|
76
|
+
elif len(edge) == 3:
|
|
77
|
+
g.add_edge(edge[0], edge[1], weight=edge[2])
|
|
78
|
+
graph = g
|
|
79
|
+
|
|
80
|
+
self.__graph = graph
|
|
81
|
+
self.__layout = layout
|
|
82
|
+
self.__node_color = node_color
|
|
83
|
+
self.__node_size = node_size
|
|
84
|
+
self.__edge_color = edge_color
|
|
85
|
+
self.__with_labels = with_labels
|
|
86
|
+
self.__kwargs = kwargs
|
|
87
|
+
|
|
88
|
+
super().__init__(backend=backend, title=title)
|
|
89
|
+
self._render()
|
|
90
|
+
|
|
91
|
+
def _compute_positions(self):
|
|
92
|
+
"""Map the ``layout`` name to the corresponding networkx function."""
|
|
93
|
+
layouts = {
|
|
94
|
+
"spring": nx.spring_layout,
|
|
95
|
+
"circular": nx.circular_layout,
|
|
96
|
+
"kamada_kawai": nx.kamada_kawai_layout,
|
|
97
|
+
"random": nx.random_layout,
|
|
98
|
+
"shell": nx.shell_layout,
|
|
99
|
+
}
|
|
100
|
+
if self.__layout not in layouts:
|
|
101
|
+
raise ValueError(
|
|
102
|
+
f"Unknown layout {self.__layout!r}. Choose from {list(layouts)}."
|
|
103
|
+
)
|
|
104
|
+
return layouts[self.__layout](self.__graph)
|
|
105
|
+
|
|
106
|
+
def _plot_seaborn(self):
|
|
107
|
+
"""Render using :func:`networkx.draw`."""
|
|
108
|
+
pos = self._compute_positions()
|
|
109
|
+
nx.draw(
|
|
110
|
+
self.__graph,
|
|
111
|
+
pos=pos,
|
|
112
|
+
node_color=self.__node_color,
|
|
113
|
+
node_size=self.__node_size,
|
|
114
|
+
edge_color=self.__edge_color,
|
|
115
|
+
with_labels=self.__with_labels,
|
|
116
|
+
**self.__kwargs,
|
|
117
|
+
)
|
|
118
|
+
if self._title:
|
|
119
|
+
plt.title(self._title)
|
|
120
|
+
|
|
121
|
+
def _plot_plotly(self):
|
|
122
|
+
"""Render with Plotly by building edge + node scatter traces."""
|
|
123
|
+
pos = self._compute_positions()
|
|
124
|
+
|
|
125
|
+
# One edge trace: all edges drawn as a single scatter with None
|
|
126
|
+
# separators so we only issue a single add_trace for all edges.
|
|
127
|
+
edge_x, edge_y = [], []
|
|
128
|
+
for u, v in self.__graph.edges():
|
|
129
|
+
x0, y0 = pos[u]
|
|
130
|
+
x1, y1 = pos[v]
|
|
131
|
+
edge_x += [x0, x1, None]
|
|
132
|
+
edge_y += [y0, y1, None]
|
|
133
|
+
|
|
134
|
+
edge_trace = go.Scatter(
|
|
135
|
+
x=edge_x,
|
|
136
|
+
y=edge_y,
|
|
137
|
+
line=dict(width=1, color=self.__edge_color),
|
|
138
|
+
hoverinfo="none",
|
|
139
|
+
mode="lines",
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
# Node trace carries labels via text / hovertext.
|
|
143
|
+
node_x, node_y, node_text = [], [], []
|
|
144
|
+
for node in self.__graph.nodes():
|
|
145
|
+
x, y = pos[node]
|
|
146
|
+
node_x.append(x)
|
|
147
|
+
node_y.append(y)
|
|
148
|
+
node_text.append(str(node))
|
|
149
|
+
|
|
150
|
+
node_trace = go.Scatter(
|
|
151
|
+
x=node_x,
|
|
152
|
+
y=node_y,
|
|
153
|
+
mode="markers+text" if self.__with_labels else "markers",
|
|
154
|
+
text=node_text,
|
|
155
|
+
textposition="top center",
|
|
156
|
+
marker=dict(size=12, color=self.__node_color),
|
|
157
|
+
hoverinfo="text",
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
fig = go.Figure(data=[edge_trace, node_trace])
|
|
161
|
+
fig.update_layout(
|
|
162
|
+
title=self._title,
|
|
163
|
+
showlegend=False,
|
|
164
|
+
xaxis=dict(showgrid=False, zeroline=False, visible=False),
|
|
165
|
+
yaxis=dict(showgrid=False, zeroline=False, visible=False),
|
|
166
|
+
)
|
|
167
|
+
self._fig = fig
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.network.sankey_diagram
|
|
3
|
+
==============================
|
|
4
|
+
|
|
5
|
+
Dual-backend Sankey diagram — a flow diagram where band width encodes
|
|
6
|
+
quantity.
|
|
7
|
+
|
|
8
|
+
The Plotly backend uses :class:`plotly.graph_objects.Sankey`. The Seaborn
|
|
9
|
+
backend renders a custom layered layout: nodes are placed in columns by
|
|
10
|
+
graph depth (BFS from the sources), each node's vertical extent is
|
|
11
|
+
proportional to its flow throughput, and flows are drawn as cubic Bezier
|
|
12
|
+
ribbons connecting source to target. This is much cleaner than the
|
|
13
|
+
output of :class:`matplotlib.sankey.Sankey`, which is built around
|
|
14
|
+
per-block flow conservation and produces overlapping shapes for
|
|
15
|
+
arbitrary bipartite / multi-stage flows.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import matplotlib.patches as patches
|
|
19
|
+
import matplotlib.pyplot as plt
|
|
20
|
+
import plotly.graph_objects as go
|
|
21
|
+
from matplotlib.path import Path
|
|
22
|
+
|
|
23
|
+
from plotify.base import BasePlot
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SankeyDiagram(BasePlot):
|
|
27
|
+
"""
|
|
28
|
+
Sankey flow diagram.
|
|
29
|
+
|
|
30
|
+
Provide the flows as three parallel lists — ``source``, ``target``, and
|
|
31
|
+
``value`` — plus ``labels``. ``source`` and ``target`` contain integer
|
|
32
|
+
indices into ``labels``.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
source,
|
|
38
|
+
target,
|
|
39
|
+
value,
|
|
40
|
+
labels,
|
|
41
|
+
colors=None,
|
|
42
|
+
title=None,
|
|
43
|
+
backend="seaborn",
|
|
44
|
+
**kwargs,
|
|
45
|
+
):
|
|
46
|
+
"""
|
|
47
|
+
This is used to create a Sankey diagram.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
source : list[int]
|
|
52
|
+
Index of the source node for each flow.
|
|
53
|
+
target : list[int]
|
|
54
|
+
Index of the target node for each flow.
|
|
55
|
+
value : list[float]
|
|
56
|
+
Magnitude of each flow.
|
|
57
|
+
labels : list[str]
|
|
58
|
+
Node labels; ``source`` and ``target`` index into this list.
|
|
59
|
+
colors : list[str], optional
|
|
60
|
+
Colour per node (Plotly only).
|
|
61
|
+
title : str, optional
|
|
62
|
+
Plot title.
|
|
63
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
64
|
+
Rendering backend.
|
|
65
|
+
**kwargs :
|
|
66
|
+
Forwarded to the underlying library.
|
|
67
|
+
|
|
68
|
+
Returns
|
|
69
|
+
-------
|
|
70
|
+
None
|
|
71
|
+
"""
|
|
72
|
+
if not (len(source) == len(target) == len(value)):
|
|
73
|
+
raise ValueError("`source`, `target`, and `value` must all have the same length.")
|
|
74
|
+
|
|
75
|
+
self.__source = list(source)
|
|
76
|
+
self.__target = list(target)
|
|
77
|
+
self.__value = list(value)
|
|
78
|
+
self.__labels = list(labels)
|
|
79
|
+
self.__colors = colors
|
|
80
|
+
self.__kwargs = kwargs
|
|
81
|
+
|
|
82
|
+
super().__init__(backend=backend, title=title)
|
|
83
|
+
self._render()
|
|
84
|
+
|
|
85
|
+
def _plot_seaborn(self):
|
|
86
|
+
"""Render a layered Sankey using matplotlib primitives directly.
|
|
87
|
+
|
|
88
|
+
Compute per-node throughput, lay out nodes in columns by graph
|
|
89
|
+
depth, then draw each flow as a cubic-Bezier ribbon whose width
|
|
90
|
+
encodes its value. Avoids :class:`matplotlib.sankey.Sankey`,
|
|
91
|
+
which produces poor output for non-trivial multi-stage flows.
|
|
92
|
+
"""
|
|
93
|
+
n = len(self.__labels)
|
|
94
|
+
|
|
95
|
+
# ---- Per-node incoming and outgoing throughput totals. -----------
|
|
96
|
+
in_totals = [0.0] * n
|
|
97
|
+
out_totals = [0.0] * n
|
|
98
|
+
for s, t, v in zip(self.__source, self.__target, self.__value):
|
|
99
|
+
out_totals[s] += v
|
|
100
|
+
in_totals[t] += v
|
|
101
|
+
|
|
102
|
+
# ---- Assign each node to a column via a longest-path pass. -------
|
|
103
|
+
# Sources (no incoming edges) are level 0. Each downstream node sits
|
|
104
|
+
# at max(predecessor levels) + 1. The fixed-point loop terminates
|
|
105
|
+
# because levels only increase.
|
|
106
|
+
levels: dict[int, int] = {
|
|
107
|
+
i: 0 for i in range(n) if in_totals[i] == 0
|
|
108
|
+
}
|
|
109
|
+
changed = True
|
|
110
|
+
while changed:
|
|
111
|
+
changed = False
|
|
112
|
+
for s, t in zip(self.__source, self.__target):
|
|
113
|
+
if s in levels:
|
|
114
|
+
candidate = levels[s] + 1
|
|
115
|
+
if t not in levels or levels[t] < candidate:
|
|
116
|
+
levels[t] = candidate
|
|
117
|
+
changed = True
|
|
118
|
+
# Any node still unassigned (cyclic graph) — pin to the last column.
|
|
119
|
+
max_level = max(levels.values(), default=0)
|
|
120
|
+
for i in range(n):
|
|
121
|
+
levels.setdefault(i, max_level + 1)
|
|
122
|
+
max_level = max(levels.values())
|
|
123
|
+
|
|
124
|
+
by_level: dict[int, list[int]] = {}
|
|
125
|
+
for i, level in levels.items():
|
|
126
|
+
by_level.setdefault(level, []).append(i)
|
|
127
|
+
|
|
128
|
+
# ---- Compute node positions in a [0, 1] x [0, 1] viewport. -------
|
|
129
|
+
# Node height ∝ max(in, out) so every flow has equal width on both
|
|
130
|
+
# ends of the ribbon.
|
|
131
|
+
heights = {i: max(in_totals[i], out_totals[i]) for i in range(n)}
|
|
132
|
+
gap = 0.02
|
|
133
|
+
node_width = 0.025
|
|
134
|
+
positions: dict[int, tuple[float, float, float]] = {} # node -> (x, y_top, y_bot)
|
|
135
|
+
n_levels = max_level + 1
|
|
136
|
+
for level, nodes in sorted(by_level.items()):
|
|
137
|
+
total = sum(heights[i] for i in nodes)
|
|
138
|
+
usable = 1.0 - gap * max(len(nodes) - 1, 0)
|
|
139
|
+
scale = usable / total if total else 0
|
|
140
|
+
x = level / max(n_levels - 1, 1) if n_levels > 1 else 0.5
|
|
141
|
+
y = 1.0
|
|
142
|
+
for n_id in nodes:
|
|
143
|
+
h = heights[n_id] * scale
|
|
144
|
+
positions[n_id] = (x, y, y - h)
|
|
145
|
+
y -= h + gap
|
|
146
|
+
|
|
147
|
+
# ---- Draw. -------------------------------------------------------
|
|
148
|
+
fig, ax = plt.subplots()
|
|
149
|
+
ax.set_xlim(-0.18, 1.18)
|
|
150
|
+
ax.set_ylim(-0.05, 1.08)
|
|
151
|
+
ax.axis("off")
|
|
152
|
+
|
|
153
|
+
cmap = plt.get_cmap("tab10")
|
|
154
|
+
|
|
155
|
+
# Track running fill offsets so multiple flows out of (or into) a
|
|
156
|
+
# node stack neatly without overlapping.
|
|
157
|
+
out_used = {i: 0.0 for i in range(n)}
|
|
158
|
+
in_used = {i: 0.0 for i in range(n)}
|
|
159
|
+
|
|
160
|
+
# Flow ribbons first so node rectangles overlay them.
|
|
161
|
+
for s, t, v in zip(self.__source, self.__target, self.__value):
|
|
162
|
+
xs, y_s_top, y_s_bot = positions[s]
|
|
163
|
+
xt, y_t_top, y_t_bot = positions[t]
|
|
164
|
+
scale_s = (y_s_top - y_s_bot) / out_totals[s] if out_totals[s] else 0
|
|
165
|
+
scale_t = (y_t_top - y_t_bot) / in_totals[t] if in_totals[t] else 0
|
|
166
|
+
v_s = v * scale_s
|
|
167
|
+
v_t = v * scale_t
|
|
168
|
+
s_top = y_s_top - out_used[s]
|
|
169
|
+
s_bot = s_top - v_s
|
|
170
|
+
t_top = y_t_top - in_used[t]
|
|
171
|
+
t_bot = t_top - v_t
|
|
172
|
+
out_used[s] += v_s
|
|
173
|
+
in_used[t] += v_t
|
|
174
|
+
|
|
175
|
+
mid_x = (xs + xt) / 2
|
|
176
|
+
x_left = xs + node_width / 2
|
|
177
|
+
x_right = xt - node_width / 2
|
|
178
|
+
|
|
179
|
+
# Build a closed path: top edge (left → right) as a Bezier, a
|
|
180
|
+
# straight line down at the right node, bottom edge (right → left)
|
|
181
|
+
# as a Bezier, and a straight line up at the left node.
|
|
182
|
+
verts = [
|
|
183
|
+
(x_left, s_top),
|
|
184
|
+
(mid_x, s_top), (mid_x, t_top), (x_right, t_top),
|
|
185
|
+
(x_right, t_bot),
|
|
186
|
+
(mid_x, t_bot), (mid_x, s_bot), (x_left, s_bot),
|
|
187
|
+
(x_left, s_top),
|
|
188
|
+
]
|
|
189
|
+
codes = [
|
|
190
|
+
Path.MOVETO,
|
|
191
|
+
Path.CURVE4, Path.CURVE4, Path.CURVE4,
|
|
192
|
+
Path.LINETO,
|
|
193
|
+
Path.CURVE4, Path.CURVE4, Path.CURVE4,
|
|
194
|
+
Path.CLOSEPOLY,
|
|
195
|
+
]
|
|
196
|
+
ax.add_patch(
|
|
197
|
+
patches.PathPatch(
|
|
198
|
+
Path(verts, codes),
|
|
199
|
+
facecolor=cmap(s % 10),
|
|
200
|
+
alpha=0.35,
|
|
201
|
+
edgecolor="none",
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
# Node rectangles + labels.
|
|
206
|
+
for n_id, (x, y_top, y_bot) in positions.items():
|
|
207
|
+
ax.add_patch(
|
|
208
|
+
patches.Rectangle(
|
|
209
|
+
(x - node_width / 2, y_bot),
|
|
210
|
+
node_width,
|
|
211
|
+
y_top - y_bot,
|
|
212
|
+
facecolor=cmap(n_id % 10),
|
|
213
|
+
edgecolor="black",
|
|
214
|
+
linewidth=0.5,
|
|
215
|
+
)
|
|
216
|
+
)
|
|
217
|
+
label = self.__labels[n_id]
|
|
218
|
+
level = levels[n_id]
|
|
219
|
+
if level == 0:
|
|
220
|
+
ax.text(
|
|
221
|
+
x - node_width, (y_top + y_bot) / 2, label,
|
|
222
|
+
ha="right", va="center", fontsize=9,
|
|
223
|
+
)
|
|
224
|
+
elif level == max_level:
|
|
225
|
+
ax.text(
|
|
226
|
+
x + node_width, (y_top + y_bot) / 2, label,
|
|
227
|
+
ha="left", va="center", fontsize=9,
|
|
228
|
+
)
|
|
229
|
+
else:
|
|
230
|
+
ax.text(
|
|
231
|
+
x, y_top + 0.012, label,
|
|
232
|
+
ha="center", va="bottom", fontsize=8,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
if self._title:
|
|
236
|
+
ax.set_title(self._title)
|
|
237
|
+
|
|
238
|
+
def _plot_plotly(self):
|
|
239
|
+
"""Render using :class:`plotly.graph_objects.Sankey`."""
|
|
240
|
+
node_dict = dict(label=self.__labels)
|
|
241
|
+
if self.__colors:
|
|
242
|
+
node_dict["color"] = self.__colors
|
|
243
|
+
|
|
244
|
+
fig = go.Figure(
|
|
245
|
+
data=[
|
|
246
|
+
go.Sankey(
|
|
247
|
+
node=node_dict,
|
|
248
|
+
link=dict(
|
|
249
|
+
source=self.__source,
|
|
250
|
+
target=self.__target,
|
|
251
|
+
value=self.__value,
|
|
252
|
+
),
|
|
253
|
+
)
|
|
254
|
+
]
|
|
255
|
+
)
|
|
256
|
+
if self._title:
|
|
257
|
+
fig.update_layout(title=self._title)
|
|
258
|
+
self._fig = fig
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.num_cat
|
|
3
|
+
===============
|
|
4
|
+
|
|
5
|
+
Plots combining numeric and categorical variables: GroupedBarPlot,
|
|
6
|
+
StackedBarPlot, GroupedScatter, BoxPlotByGroup.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from plotify.num_cat.box_plot_by_group import BoxPlotByGroup
|
|
10
|
+
from plotify.num_cat.grouped_bar_plot import GroupedBarPlot
|
|
11
|
+
from plotify.num_cat.grouped_scatter import GroupedScatter
|
|
12
|
+
from plotify.num_cat.stacked_bar_plot import StackedBarPlot
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"BoxPlotByGroup",
|
|
16
|
+
"GroupedBarPlot",
|
|
17
|
+
"GroupedScatter",
|
|
18
|
+
"StackedBarPlot",
|
|
19
|
+
]
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.num_cat.box_plot_by_group
|
|
3
|
+
=================================
|
|
4
|
+
|
|
5
|
+
Box plots grouped by a secondary categorical variable — one cluster of
|
|
6
|
+
boxes per primary category.
|
|
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 BoxPlotByGroup(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Box plots split by a secondary (hue) categorical variable.
|
|
19
|
+
|
|
20
|
+
Equivalent to :class:`plotify.numerical.Boxplot` with mandatory ``hue``;
|
|
21
|
+
exposed as its own class to keep numeric-only and grouped use cases
|
|
22
|
+
discoverable from separate subpackages.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
df,
|
|
28
|
+
x,
|
|
29
|
+
y,
|
|
30
|
+
hue,
|
|
31
|
+
order=None,
|
|
32
|
+
hue_order=None,
|
|
33
|
+
palette=None,
|
|
34
|
+
title=None,
|
|
35
|
+
backend="seaborn",
|
|
36
|
+
**kwargs,
|
|
37
|
+
):
|
|
38
|
+
"""
|
|
39
|
+
This is used to create box plots grouped by a sub-category.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
df : pandas.DataFrame
|
|
44
|
+
Input data.
|
|
45
|
+
x : str
|
|
46
|
+
Primary categorical axis.
|
|
47
|
+
y : str
|
|
48
|
+
Numeric column being summarised.
|
|
49
|
+
hue : str
|
|
50
|
+
Secondary categorical column — produces parallel boxes within
|
|
51
|
+
each primary category.
|
|
52
|
+
order, hue_order : list, optional
|
|
53
|
+
Explicit category ordering.
|
|
54
|
+
palette : str or list, optional
|
|
55
|
+
Colour palette.
|
|
56
|
+
title : str, optional
|
|
57
|
+
Plot title.
|
|
58
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
59
|
+
Rendering backend.
|
|
60
|
+
**kwargs :
|
|
61
|
+
Forwarded to the underlying library.
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
None
|
|
66
|
+
"""
|
|
67
|
+
self.__df = df
|
|
68
|
+
self.__x = x
|
|
69
|
+
self.__y = y
|
|
70
|
+
self.__hue = hue
|
|
71
|
+
self.__order = order
|
|
72
|
+
self.__hue_order = hue_order
|
|
73
|
+
self.__palette = palette
|
|
74
|
+
self.__kwargs = kwargs
|
|
75
|
+
|
|
76
|
+
super().__init__(backend=backend, title=title)
|
|
77
|
+
self._render()
|
|
78
|
+
|
|
79
|
+
def _plot_seaborn(self):
|
|
80
|
+
"""Render using :func:`seaborn.boxplot` with hue grouping."""
|
|
81
|
+
sns.boxplot(
|
|
82
|
+
data=self.__df,
|
|
83
|
+
x=self.__x,
|
|
84
|
+
y=self.__y,
|
|
85
|
+
hue=self.__hue,
|
|
86
|
+
order=self.__order,
|
|
87
|
+
hue_order=self.__hue_order,
|
|
88
|
+
palette=self.__palette,
|
|
89
|
+
**self.__kwargs,
|
|
90
|
+
)
|
|
91
|
+
if self._title:
|
|
92
|
+
plt.title(self._title)
|
|
93
|
+
|
|
94
|
+
def _plot_plotly(self):
|
|
95
|
+
"""Render using :func:`plotly.express.box`."""
|
|
96
|
+
fig = px.box(
|
|
97
|
+
self.__df,
|
|
98
|
+
x=self.__x,
|
|
99
|
+
y=self.__y,
|
|
100
|
+
color=self.__hue,
|
|
101
|
+
category_orders={
|
|
102
|
+
self.__x: self.__order,
|
|
103
|
+
self.__hue: self.__hue_order,
|
|
104
|
+
}
|
|
105
|
+
if (self.__order or self.__hue_order)
|
|
106
|
+
else None,
|
|
107
|
+
title=self._title,
|
|
108
|
+
**self.__kwargs,
|
|
109
|
+
)
|
|
110
|
+
self._fig = fig
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.num_cat.grouped_bar_plot
|
|
3
|
+
================================
|
|
4
|
+
|
|
5
|
+
Grouped (side-by-side) bar plot for comparing a numeric value across one
|
|
6
|
+
categorical axis and one sub-group axis.
|
|
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 GroupedBarPlot(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Grouped bar plot.
|
|
19
|
+
|
|
20
|
+
A primary category on the x axis, a secondary category that splits each
|
|
21
|
+
primary bar into side-by-side sub-bars, and a numeric y axis.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
df,
|
|
27
|
+
x,
|
|
28
|
+
y,
|
|
29
|
+
hue,
|
|
30
|
+
order=None,
|
|
31
|
+
hue_order=None,
|
|
32
|
+
palette=None,
|
|
33
|
+
title=None,
|
|
34
|
+
backend="seaborn",
|
|
35
|
+
**kwargs,
|
|
36
|
+
):
|
|
37
|
+
"""
|
|
38
|
+
This is used to create a grouped bar plot.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
df : pandas.DataFrame
|
|
43
|
+
Input data.
|
|
44
|
+
x : str
|
|
45
|
+
Primary categorical column.
|
|
46
|
+
y : str
|
|
47
|
+
Numeric value column.
|
|
48
|
+
hue : str
|
|
49
|
+
Sub-group categorical column — each value becomes a sub-bar.
|
|
50
|
+
order, hue_order : list, optional
|
|
51
|
+
Explicit category ordering.
|
|
52
|
+
palette : str or list, optional
|
|
53
|
+
Colour palette.
|
|
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
|
+
self.__df = df
|
|
66
|
+
self.__x = x
|
|
67
|
+
self.__y = y
|
|
68
|
+
self.__hue = hue
|
|
69
|
+
self.__order = order
|
|
70
|
+
self.__hue_order = hue_order
|
|
71
|
+
self.__palette = palette
|
|
72
|
+
self.__kwargs = kwargs
|
|
73
|
+
|
|
74
|
+
super().__init__(backend=backend, title=title)
|
|
75
|
+
self._render()
|
|
76
|
+
|
|
77
|
+
def _plot_seaborn(self):
|
|
78
|
+
"""Render using :func:`seaborn.barplot` with ``dodge=True``."""
|
|
79
|
+
sns.barplot(
|
|
80
|
+
data=self.__df,
|
|
81
|
+
x=self.__x,
|
|
82
|
+
y=self.__y,
|
|
83
|
+
hue=self.__hue,
|
|
84
|
+
order=self.__order,
|
|
85
|
+
hue_order=self.__hue_order,
|
|
86
|
+
palette=self.__palette,
|
|
87
|
+
dodge=True,
|
|
88
|
+
**self.__kwargs,
|
|
89
|
+
)
|
|
90
|
+
if self._title:
|
|
91
|
+
plt.title(self._title)
|
|
92
|
+
|
|
93
|
+
def _plot_plotly(self):
|
|
94
|
+
"""Render using :func:`plotly.express.bar` with ``barmode='group'``."""
|
|
95
|
+
fig = px.bar(
|
|
96
|
+
self.__df,
|
|
97
|
+
x=self.__x,
|
|
98
|
+
y=self.__y,
|
|
99
|
+
color=self.__hue,
|
|
100
|
+
barmode="group",
|
|
101
|
+
category_orders={
|
|
102
|
+
self.__x: self.__order,
|
|
103
|
+
self.__hue: self.__hue_order,
|
|
104
|
+
}
|
|
105
|
+
if (self.__order or self.__hue_order)
|
|
106
|
+
else None,
|
|
107
|
+
title=self._title,
|
|
108
|
+
**self.__kwargs,
|
|
109
|
+
)
|
|
110
|
+
self._fig = fig
|