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.
Files changed (50) hide show
  1. plotify/__init__.py +116 -0
  2. plotify/_inference.py +144 -0
  3. plotify/auto.py +360 -0
  4. plotify/base.py +224 -0
  5. plotify/categorical/__init__.py +37 -0
  6. plotify/categorical/bar_plot.py +121 -0
  7. plotify/categorical/circular_packing.py +107 -0
  8. plotify/categorical/dendrogram.py +113 -0
  9. plotify/categorical/doughnut_chart.py +109 -0
  10. plotify/categorical/lollipop_chart.py +168 -0
  11. plotify/categorical/parallel_coordinates.py +94 -0
  12. plotify/categorical/pie_chart.py +101 -0
  13. plotify/categorical/radar_chart.py +116 -0
  14. plotify/categorical/sunburst_diagram.py +117 -0
  15. plotify/categorical/treemap.py +121 -0
  16. plotify/categorical/venn_diagram.py +92 -0
  17. plotify/categorical/word_cloud.py +104 -0
  18. plotify/maps/__init__.py +21 -0
  19. plotify/maps/bubble_map.py +114 -0
  20. plotify/maps/cartogram.py +126 -0
  21. plotify/maps/choropleth_map.py +108 -0
  22. plotify/maps/connection_map.py +117 -0
  23. plotify/maps/hexbin_map.py +96 -0
  24. plotify/network/__init__.py +21 -0
  25. plotify/network/arc_diagram.py +124 -0
  26. plotify/network/chord_diagram.py +119 -0
  27. plotify/network/hierarchical_edge_bundling.py +141 -0
  28. plotify/network/network_diagram.py +167 -0
  29. plotify/network/sankey_diagram.py +258 -0
  30. plotify/num_cat/__init__.py +19 -0
  31. plotify/num_cat/box_plot_by_group.py +110 -0
  32. plotify/num_cat/grouped_bar_plot.py +110 -0
  33. plotify/num_cat/grouped_scatter.py +105 -0
  34. plotify/num_cat/stacked_bar_plot.py +117 -0
  35. plotify/numerical/__init__.py +21 -0
  36. plotify/numerical/boxplot.py +157 -0
  37. plotify/numerical/connected_scatter_plot.py +120 -0
  38. plotify/numerical/density_plot.py +184 -0
  39. plotify/numerical/scatter_plot.py +140 -0
  40. plotify/numerical/violin_plot.py +141 -0
  41. plotify/theme.py +297 -0
  42. plotify/timeseries/__init__.py +13 -0
  43. plotify/timeseries/area_chart.py +89 -0
  44. plotify/timeseries/line_chart.py +110 -0
  45. plotify/timeseries/stacked_area_chart.py +133 -0
  46. plotify/timeseries/stream_graph.py +116 -0
  47. plotify_charts-0.1.0.dist-info/LICENSE +21 -0
  48. plotify_charts-0.1.0.dist-info/METADATA +226 -0
  49. plotify_charts-0.1.0.dist-info/RECORD +50 -0
  50. plotify_charts-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,140 @@
1
+ """
2
+ plotify.numerical.scatter_plot
3
+ ==============================
4
+
5
+ Dual-backend scatter plot, optionally with a regression line.
6
+ """
7
+
8
+ import matplotlib.pyplot as plt
9
+ import plotly.express as px
10
+ import seaborn as sns
11
+
12
+ from plotify.base import BasePlot
13
+
14
+
15
+ class ScatterPlot(BasePlot):
16
+ """
17
+ Scatter plot with optional regression overlay.
18
+
19
+ The ``style`` parameter selects the Seaborn variant:
20
+
21
+ * ``"scatter"`` → :func:`seaborn.scatterplot` (default)
22
+ * ``"reg"`` → :func:`seaborn.regplot`
23
+ * ``"lm"`` → :func:`seaborn.lmplot`
24
+
25
+ On the Plotly backend, any ``style != "scatter"`` is rendered through
26
+ :func:`plotly.express.scatter` with ``trendline="ols"``.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ df,
32
+ x=None,
33
+ y=None,
34
+ plots=None,
35
+ style="scatter",
36
+ ax=None,
37
+ title=None,
38
+ default_style=None,
39
+ backend="seaborn",
40
+ **kwargs,
41
+ ):
42
+ """
43
+ This is used to create scatter plots using seaborn or plotly.
44
+
45
+ Parameters
46
+ ----------
47
+ df : pandas.DataFrame
48
+ The data to plot.
49
+ x, y : str, optional
50
+ Column names for the x- and y-axes (used for a single basic plot).
51
+ plots : list[dict], optional
52
+ List of per-series parameter dicts. Each dict must contain at
53
+ minimum ``"x"`` and ``"y"`` keys.
54
+ style : {"scatter", "reg", "lm"}, default="scatter"
55
+ Which Seaborn function / Plotly trendline to use.
56
+ ax : matplotlib.axes.Axes, optional
57
+ Pre-existing axes for the seaborn backend.
58
+ title : str, optional
59
+ Plot title.
60
+ default_style : dict, optional
61
+ Shared keyword arguments merged into each plot spec when ``plots``
62
+ is not provided and a single ``(x, y)`` is used.
63
+ backend : {"seaborn", "plotly"}, default="seaborn"
64
+ Rendering backend.
65
+ **kwargs :
66
+ Forwarded to the underlying library function.
67
+
68
+ Returns
69
+ -------
70
+ None
71
+ """
72
+ self.__df = df
73
+ self.__plots = plots or []
74
+ self.__style = style
75
+ self.__ax = ax
76
+ self.__default_style = default_style or {}
77
+ self.__kwargs = kwargs
78
+
79
+ # When only x/y are supplied, build a single-entry spec list so both
80
+ # backends can iterate the same way.
81
+ if x and y:
82
+ self.__plots = [{"x": x, "y": y, **self.__default_style, **kwargs}]
83
+
84
+ super().__init__(backend=backend, title=title)
85
+ self._render()
86
+
87
+ def _plot_seaborn(self):
88
+ """Render via Seaborn using the chosen ``style``."""
89
+ sns.set_style("darkgrid")
90
+
91
+ for plot in self.__plots:
92
+ # Copy so we don't mutate the caller's dict across renders.
93
+ spec = dict(plot)
94
+ x = spec.pop("x")
95
+ y = spec.pop("y")
96
+
97
+ if self.__style == "lm":
98
+ # lmplot creates its own figure — no ax= allowed.
99
+ sns.lmplot(x=x, y=y, data=self.__df, **spec)
100
+ elif self.__style == "reg":
101
+ sns.regplot(
102
+ x=self.__df[x], y=self.__df[y], ax=self.__ax, **spec
103
+ )
104
+ else:
105
+ sns.scatterplot(
106
+ x=self.__df[x], y=self.__df[y], ax=self.__ax, **spec
107
+ )
108
+
109
+ if self._title and self.__ax is not None:
110
+ self.__ax.set_title(self._title)
111
+ elif self._title:
112
+ plt.title(self._title)
113
+
114
+ def _plot_plotly(self):
115
+ """Render via Plotly Express, overlaying every series onto one figure."""
116
+ fig = None
117
+ # Build one figure layering each spec as a separate series.
118
+ for plot in self.__plots:
119
+ spec = dict(plot)
120
+ x = spec.pop("x")
121
+ y = spec.pop("y")
122
+
123
+ # Regression overlays use px's built-in OLS trendline.
124
+ trendline = "ols" if self.__style in ("reg", "lm") else None
125
+
126
+ series_fig = px.scatter(
127
+ self.__df,
128
+ x=x,
129
+ y=y,
130
+ trendline=trendline,
131
+ title=self._title,
132
+ )
133
+ if fig is None:
134
+ fig = series_fig
135
+ else:
136
+ # Append each trace from the second+ spec onto the primary fig.
137
+ for trace in series_fig.data:
138
+ fig.add_trace(trace)
139
+
140
+ self._fig = fig
@@ -0,0 +1,141 @@
1
+ """
2
+ plotify.numerical.violin_plot
3
+ =============================
4
+
5
+ Dual-backend violin plot wrapping :func:`seaborn.violinplot` and
6
+ :func:`plotly.express.violin`.
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 Violinplot(BasePlot):
17
+ """
18
+ Violin plot: a KDE mirrored around a central axis, optionally with an
19
+ inner box/quartile/stick representation of the raw data.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ df,
25
+ x=None,
26
+ y=None,
27
+ hue=None,
28
+ order=None,
29
+ hue_order=None,
30
+ bw="scott",
31
+ cut=2,
32
+ scale="area",
33
+ scale_hue=True,
34
+ gridsize=100,
35
+ width=0.8,
36
+ inner="box",
37
+ split=False,
38
+ dodge=True,
39
+ orient=None,
40
+ linewidth=None,
41
+ color=None,
42
+ palette=None,
43
+ saturation=0.75,
44
+ ax=None,
45
+ title=None,
46
+ backend="seaborn",
47
+ **kwargs,
48
+ ):
49
+ """
50
+ This is used to create violinplot figures.
51
+
52
+ Parameters mirror :func:`seaborn.violinplot` where applicable; refer
53
+ there for detail. ``backend`` selects between Seaborn and Plotly.
54
+
55
+ Parameters
56
+ ----------
57
+ df : pandas.DataFrame or array-like
58
+ The data to plot. DataFrame preferred.
59
+ x, y, hue : str, optional
60
+ Variables used for plotting.
61
+ backend : {"seaborn", "plotly"}, default="seaborn"
62
+ Rendering backend.
63
+ **kwargs :
64
+ Forwarded to the underlying library.
65
+
66
+ Returns
67
+ -------
68
+ None
69
+ """
70
+ self.__df = df
71
+ self.__x = x
72
+ self.__y = y
73
+ self.__hue = hue
74
+ self.__order = order
75
+ self.__hue_order = hue_order
76
+ self.__bw = bw
77
+ self.__cut = cut
78
+ self.__scale = scale
79
+ self.__scale_hue = scale_hue
80
+ self.__gridsize = gridsize
81
+ self.__width = width
82
+ self.__inner = inner
83
+ self.__split = split
84
+ self.__dodge = dodge
85
+ self.__orient = orient
86
+ self.__linewidth = linewidth
87
+ self.__color = color
88
+ self.__palette = palette
89
+ self.__saturation = saturation
90
+ self.__ax = ax
91
+ self.__kwargs = kwargs
92
+
93
+ super().__init__(backend=backend, title=title)
94
+ self._render()
95
+
96
+ def _plot_seaborn(self):
97
+ """Render using :func:`seaborn.violinplot`."""
98
+ # Newer seaborn versions renamed ``bw`` to ``bw_method``. We pass via
99
+ # kwargs after catching the legacy name so older installs still work.
100
+ sns.violinplot(
101
+ x=self.__x,
102
+ y=self.__y,
103
+ hue=self.__hue,
104
+ data=self.__df,
105
+ order=self.__order,
106
+ hue_order=self.__hue_order,
107
+ cut=self.__cut,
108
+ gridsize=self.__gridsize,
109
+ width=self.__width,
110
+ inner=self.__inner,
111
+ split=self.__split,
112
+ dodge=self.__dodge,
113
+ orient=self.__orient,
114
+ linewidth=self.__linewidth,
115
+ color=self.__color,
116
+ palette=self.__palette,
117
+ saturation=self.__saturation,
118
+ ax=self.__ax,
119
+ **self.__kwargs,
120
+ )
121
+ if self._title:
122
+ plt.title(self._title)
123
+
124
+ def _plot_plotly(self):
125
+ """Render using :func:`plotly.express.violin`."""
126
+ # Plotly's violin supports ``box`` and ``points`` toggles; map the
127
+ # seaborn ``inner`` to the closest equivalent.
128
+ inner_box = self.__inner == "box"
129
+ points = "all" if self.__inner in ("point", "stick") else False
130
+
131
+ fig = px.violin(
132
+ self.__df,
133
+ x=self.__x,
134
+ y=self.__y,
135
+ color=self.__hue,
136
+ box=inner_box,
137
+ points=points,
138
+ title=self._title,
139
+ **self.__kwargs,
140
+ )
141
+ self._fig = fig
plotify/theme.py ADDED
@@ -0,0 +1,297 @@
1
+ """
2
+ plotify.theme
3
+ =============
4
+
5
+ The Plotify theme system. A *theme* bundles up colour palette, fonts,
6
+ spine visibility, gridlines, and tick formatting in one place; calling
7
+ :func:`apply_current` translates the current theme into the global state
8
+ of whichever backend is about to render.
9
+
10
+ The shipped ``"publication"`` theme is applied automatically — every
11
+ Plotify plot picks it up unless the caller disables theming via
12
+ ``theme.set("none")``. Custom themes can be registered with
13
+ :func:`register`.
14
+ """
15
+
16
+ from dataclasses import dataclass, field
17
+
18
+ import matplotlib as mpl
19
+ import matplotlib.ticker as mticker
20
+ import plotly.graph_objects as go
21
+ import plotly.io as pio
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Theme:
26
+ """A single visual theme.
27
+
28
+ Attributes are intentionally backend-agnostic — the ``_apply_*`` helpers
29
+ below translate them into matplotlib rcParams or a Plotly template.
30
+ """
31
+
32
+ name: str
33
+ palette: tuple[str, ...]
34
+ background: str = "white"
35
+ grid_color: str = "#E5E5E5"
36
+ font_family: str = "DejaVu Sans"
37
+ title_size: int = 14
38
+ label_size: int = 11
39
+ tick_size: int = 10
40
+ # Which spines (axes borders) to keep visible.
41
+ spines: tuple[str, ...] = ("left", "bottom")
42
+ # If True, format large numeric ticks as 1.2K / 3.4M / 5B etc.
43
+ smart_ticks: bool = True
44
+ # Extra metadata set by helpers — not user-facing but lets the theme be
45
+ # extended without breaking the dataclass signature.
46
+ extras: dict = field(default_factory=dict)
47
+
48
+
49
+ # Okabe & Ito 2008 — colourblind-safe qualitative palette. Order chosen so
50
+ # the first 4 colours look good on bar charts, the remaining 4 fill in
51
+ # without overwhelming.
52
+ _OKABE_ITO = (
53
+ "#0072B2", # blue
54
+ "#E69F00", # orange
55
+ "#009E73", # green
56
+ "#D55E00", # vermilion
57
+ "#56B4E9", # sky blue
58
+ "#F0E442", # yellow
59
+ "#CC79A7", # purple
60
+ "#000000", # black
61
+ )
62
+
63
+
64
+ PUBLICATION = Theme(
65
+ name="publication",
66
+ palette=_OKABE_ITO,
67
+ background="white",
68
+ grid_color="#E5E5E5",
69
+ font_family="DejaVu Sans",
70
+ title_size=14,
71
+ label_size=11,
72
+ tick_size=10,
73
+ spines=("left", "bottom"),
74
+ smart_ticks=True,
75
+ )
76
+
77
+
78
+ # A no-op theme that resets matplotlib/Plotly to their library defaults.
79
+ NONE = Theme(
80
+ name="none",
81
+ palette=(),
82
+ background="white",
83
+ grid_color="#CCCCCC",
84
+ spines=("left", "bottom", "top", "right"),
85
+ smart_ticks=False,
86
+ )
87
+
88
+
89
+ # ---- registry -----------------------------------------------------------
90
+
91
+ _REGISTRY: dict[str, Theme] = {
92
+ PUBLICATION.name: PUBLICATION,
93
+ NONE.name: NONE,
94
+ }
95
+
96
+ # Module-level current theme. Defaulted to PUBLICATION so a fresh
97
+ # `import plotify` immediately produces the polished output.
98
+ _CURRENT: Theme = PUBLICATION
99
+
100
+
101
+ def register(theme: Theme) -> None:
102
+ """Register a custom theme so it can be selected by name."""
103
+ _REGISTRY[theme.name] = theme
104
+
105
+
106
+ def get_current() -> Theme:
107
+ """Return the currently active theme."""
108
+ return _CURRENT
109
+
110
+
111
+ def set(name_or_theme) -> Theme: # noqa: A001 (deliberately shadows builtin `set`)
112
+ """Switch the active theme.
113
+
114
+ Parameters
115
+ ----------
116
+ name_or_theme : str or Theme
117
+ Either the registered name of a theme (``"publication"`` /
118
+ ``"none"`` / any name passed to :func:`register`) or a
119
+ :class:`Theme` instance.
120
+
121
+ Returns
122
+ -------
123
+ Theme
124
+ The newly active theme.
125
+ """
126
+ global _CURRENT
127
+ if isinstance(name_or_theme, Theme):
128
+ _CURRENT = name_or_theme
129
+ else:
130
+ if name_or_theme not in _REGISTRY:
131
+ raise ValueError(
132
+ f"Unknown theme {name_or_theme!r}. Registered: {list(_REGISTRY)}"
133
+ )
134
+ _CURRENT = _REGISTRY[name_or_theme]
135
+ return _CURRENT
136
+
137
+
138
+ # ---- apply --------------------------------------------------------------
139
+
140
+ def apply_current(backend: str) -> None:
141
+ """Apply the current theme to a backend's global state.
142
+
143
+ Called by :class:`plotify.base.BasePlot._render` immediately before
144
+ rendering, so the most recent ``set()`` always wins.
145
+ """
146
+ if _CURRENT.name == "none":
147
+ # Skip mutation entirely so the user's pre-existing matplotlib /
148
+ # Plotly settings are preserved.
149
+ return
150
+ if backend == "seaborn":
151
+ _apply_matplotlib(_CURRENT)
152
+ else:
153
+ _apply_plotly(_CURRENT)
154
+
155
+
156
+ def _apply_matplotlib(theme: Theme) -> None:
157
+ """Translate ``theme`` into matplotlib rcParams + a default cycler."""
158
+ spines_visible = {s: (s in theme.spines) for s in ("top", "right", "left", "bottom")}
159
+
160
+ palette = list(theme.palette) or mpl.rcParams["axes.prop_cycle"].by_key().get(
161
+ "color", []
162
+ )
163
+
164
+ rc = {
165
+ # Spines
166
+ "axes.spines.top": spines_visible["top"],
167
+ "axes.spines.right": spines_visible["right"],
168
+ "axes.spines.left": spines_visible["left"],
169
+ "axes.spines.bottom": spines_visible["bottom"],
170
+ # Grid
171
+ "axes.grid": True,
172
+ "axes.grid.axis": "y",
173
+ "grid.color": theme.grid_color,
174
+ "grid.alpha": 0.6,
175
+ "grid.linewidth": 0.7,
176
+ # Type
177
+ "font.family": theme.font_family,
178
+ "axes.titlesize": theme.title_size,
179
+ "axes.titleweight": "bold",
180
+ "axes.labelsize": theme.label_size,
181
+ "xtick.labelsize": theme.tick_size,
182
+ "ytick.labelsize": theme.tick_size,
183
+ # Background
184
+ "figure.facecolor": theme.background,
185
+ "axes.facecolor": theme.background,
186
+ # Margins
187
+ "axes.titlepad": 12,
188
+ "axes.labelpad": 6,
189
+ }
190
+ if palette:
191
+ rc["axes.prop_cycle"] = mpl.cycler(color=palette)
192
+
193
+ mpl.rcParams.update(rc)
194
+
195
+
196
+ def _apply_plotly(theme: Theme) -> None:
197
+ """Build a Plotly template that mirrors ``theme`` and make it the default.
198
+
199
+ Notes
200
+ -----
201
+ We deliberately do **not** set ``tickformat`` on the axes. Setting a
202
+ numeric format such as ``"~s"`` here would apply globally and break
203
+ date axes (they would render as ``"~s"`` literals). Plotly already
204
+ auto-detects axis types and formats accordingly; users who want SI
205
+ suffixes on a specific numeric axis can opt in per-plot via
206
+ ``fig.update_yaxes(tickformat="~s")``.
207
+ """
208
+ template = go.layout.Template()
209
+ template.layout = go.Layout(
210
+ colorway=list(theme.palette),
211
+ plot_bgcolor=theme.background,
212
+ paper_bgcolor=theme.background,
213
+ font=dict(family=theme.font_family, size=theme.label_size),
214
+ title=dict(
215
+ font=dict(family=theme.font_family, size=theme.title_size),
216
+ ),
217
+ xaxis=dict(
218
+ gridcolor=theme.grid_color,
219
+ zeroline=False,
220
+ showline="bottom" in theme.spines,
221
+ linecolor="#444444",
222
+ ),
223
+ yaxis=dict(
224
+ gridcolor=theme.grid_color,
225
+ zeroline=False,
226
+ showline="left" in theme.spines,
227
+ linecolor="#444444",
228
+ ),
229
+ )
230
+ pio.templates["plotify"] = template
231
+ pio.templates.default = "plotify"
232
+
233
+
234
+ # ---- helpers ------------------------------------------------------------
235
+
236
+ def smart_formatter() -> mticker.Formatter:
237
+ """Return a matplotlib formatter that prints ``1.2K`` / ``3.4M`` / ``5B``.
238
+
239
+ Plotly applies ``tickformat="~s"`` directly via the template so this is
240
+ only used by the seaborn / matplotlib path.
241
+ """
242
+
243
+ def _fmt(value: float, _pos: int) -> str:
244
+ if value == 0:
245
+ return "0"
246
+ absval = abs(value)
247
+ # Sub-unit values: keep significant figures, no SI prefix.
248
+ if absval < 1:
249
+ return f"{value:.2g}"
250
+ if absval < 1_000:
251
+ # Drop trailing .0 for ints.
252
+ if float(value).is_integer():
253
+ return f"{int(value)}"
254
+ return f"{value:g}"
255
+ if absval < 1_000_000:
256
+ return f"{value / 1_000:.1f}K".replace(".0K", "K")
257
+ if absval < 1_000_000_000:
258
+ return f"{value / 1_000_000:.1f}M".replace(".0M", "M")
259
+ return f"{value / 1_000_000_000:.1f}B".replace(".0B", "B")
260
+
261
+ return mticker.FuncFormatter(_fmt)
262
+
263
+
264
+ def apply_smart_ticks_to_current_axes() -> None:
265
+ """Apply :func:`smart_formatter` to numeric tick axes of every open axes.
266
+
267
+ Called after a seaborn render so the tick formatting reflects the theme
268
+ even though it lives in axis-formatter space (which rcParams cannot
269
+ express directly). Wrapped in try/except per-axis so we never break a
270
+ chart that uses non-numeric ticks (dates, categories).
271
+ """
272
+ if not _CURRENT.smart_ticks or _CURRENT.name == "none":
273
+ return
274
+ import matplotlib.pyplot as plt # local: avoids import-time backend lock
275
+
276
+ for ax in plt.gcf().get_axes():
277
+ for axis in (ax.xaxis, ax.yaxis):
278
+ try:
279
+ # Only override if the axis currently uses a default scalar
280
+ # formatter — preserves date/category formatters.
281
+ if isinstance(axis.get_major_formatter(), mticker.ScalarFormatter):
282
+ axis.set_major_formatter(smart_formatter())
283
+ except Exception:
284
+ continue
285
+
286
+
287
+ __all__ = [
288
+ "Theme",
289
+ "PUBLICATION",
290
+ "NONE",
291
+ "register",
292
+ "get_current",
293
+ "set",
294
+ "apply_current",
295
+ "apply_smart_ticks_to_current_axes",
296
+ "smart_formatter",
297
+ ]
@@ -0,0 +1,13 @@
1
+ """
2
+ plotify.timeseries
3
+ ==================
4
+
5
+ Time-series plots: LineChart, AreaChart, StackedAreaChart, StreamGraph.
6
+ """
7
+
8
+ from plotify.timeseries.area_chart import AreaChart
9
+ from plotify.timeseries.line_chart import LineChart
10
+ from plotify.timeseries.stacked_area_chart import StackedAreaChart
11
+ from plotify.timeseries.stream_graph import StreamGraph
12
+
13
+ __all__ = ["AreaChart", "LineChart", "StackedAreaChart", "StreamGraph"]
@@ -0,0 +1,89 @@
1
+ """
2
+ plotify.timeseries.area_chart
3
+ =============================
4
+
5
+ Dual-backend single-series area chart — a line chart with the region under
6
+ the curve filled.
7
+ """
8
+
9
+ import matplotlib.pyplot as plt
10
+ import plotly.express as px
11
+
12
+ from plotify.base import BasePlot
13
+
14
+
15
+ class AreaChart(BasePlot):
16
+ """
17
+ Single-series filled area chart.
18
+
19
+ For multiple stacked series, see :class:`StackedAreaChart`.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ df,
25
+ x,
26
+ y,
27
+ color="steelblue",
28
+ alpha=0.4,
29
+ title=None,
30
+ backend="seaborn",
31
+ **kwargs,
32
+ ):
33
+ """
34
+ This is used to create an area chart.
35
+
36
+ Parameters
37
+ ----------
38
+ df : pandas.DataFrame
39
+ Input data.
40
+ x : str
41
+ Column for the x axis.
42
+ y : str
43
+ Numeric column whose values are filled to the x axis.
44
+ color : str, default="steelblue"
45
+ Fill colour.
46
+ alpha : float, default=0.4
47
+ Fill transparency (Seaborn only).
48
+ title : str, optional
49
+ Plot title.
50
+ backend : {"seaborn", "plotly"}, default="seaborn"
51
+ Rendering backend.
52
+ **kwargs :
53
+ Forwarded to the underlying library.
54
+
55
+ Returns
56
+ -------
57
+ None
58
+ """
59
+ self.__df = df
60
+ self.__x = x
61
+ self.__y = y
62
+ self.__color = color
63
+ self.__alpha = alpha
64
+ self.__kwargs = kwargs
65
+
66
+ super().__init__(backend=backend, title=title)
67
+ self._render()
68
+
69
+ def _plot_seaborn(self):
70
+ """Render using :func:`matplotlib.pyplot.fill_between`."""
71
+ x_vals = self.__df[self.__x]
72
+ y_vals = self.__df[self.__y]
73
+
74
+ # Draw the outline first so that the fill does not wash out the line.
75
+ plt.plot(x_vals, y_vals, color=self.__color)
76
+ plt.fill_between(x_vals, y_vals, color=self.__color, alpha=self.__alpha)
77
+ if self._title:
78
+ plt.title(self._title)
79
+
80
+ def _plot_plotly(self):
81
+ """Render using :func:`plotly.express.area`."""
82
+ fig = px.area(
83
+ self.__df,
84
+ x=self.__x,
85
+ y=self.__y,
86
+ title=self._title,
87
+ **self.__kwargs,
88
+ )
89
+ self._fig = fig