bumplot 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.
bumplot/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .main import bumplot
2
+
3
+ __version__ = "0.1.0"
4
+ __all__ = ["bumplot"]
bumplot/_utils.py ADDED
@@ -0,0 +1,28 @@
1
+ import matplotlib.pyplot as plt
2
+
3
+ import narwhals as nw
4
+ from narwhals.typing import IntoDataFrame
5
+
6
+
7
+ def _get_first_n_colors(n=int) -> list[str]:
8
+ """
9
+ Get the first n colors from matplotlib rcParams.
10
+ """
11
+ colors: list[str] = plt.rcParams["axes.prop_cycle"].by_key()["color"][:n]
12
+ return colors
13
+
14
+
15
+ def _ranked_df(df: IntoDataFrame, x: str, y_columns: list[str]):
16
+ """
17
+ Convert a dataframe to a ranked version of it.
18
+ """
19
+ df_native = nw.from_native(df).select(nw.col(x), nw.col(y_columns))
20
+
21
+ df_native_ranked = (
22
+ df_native.unpivot(on=y_columns, index=x)
23
+ .with_columns(nw.col("value").rank("ordinal").over(x))
24
+ .pivot(on="variable", index=x, values="value")
25
+ .select(nw.col(x), nw.col(y_columns))
26
+ )
27
+
28
+ return df_native_ranked
bumplot/bezier.py ADDED
@@ -0,0 +1,42 @@
1
+ from matplotlib.path import Path
2
+ import numpy as np
3
+
4
+
5
+ def bezier_curve(
6
+ x: np.ndarray,
7
+ y: np.ndarray,
8
+ force: float,
9
+ ) -> tuple[list[tuple[float, float]], list[int]]:
10
+ """
11
+ Generate vertices and path codes for a smooth cubic Bézier curve
12
+ passing through a sequence of points.
13
+
14
+ This function is used under the hood by [`bumplot()`](./bumplot.md),
15
+ but you can use it too.
16
+
17
+ Args:
18
+ x: X-coordinates of the points.
19
+ y: Y-coordinates of the points.
20
+ force: Smoothing factor controlling curve tightness. Higher values
21
+ increase curvature by moving control points further away
22
+ from the anchors.
23
+
24
+ Returns:
25
+ vertices: List of (x, y) vertices including control points for the Bézier segments.
26
+ codes: Corresponding matplotlib Path codes for constructing the curve.
27
+ """
28
+ vertices: list = []
29
+ codes: list = []
30
+
31
+ vertices.append((x[0], y[0]))
32
+ codes.append(Path.MOVETO)
33
+
34
+ for i in range(1, len(x)):
35
+ x0, y0 = x[i - 1], y[i - 1]
36
+ x1, y1 = x[i], y[i]
37
+ dx = (x1 - x0) * force
38
+
39
+ vertices.extend([(x0 + dx, y0), (x1 - dx, y1), (x1, y1)])
40
+ codes.extend([Path.CURVE4, Path.CURVE4, Path.CURVE4])
41
+
42
+ return vertices, codes
bumplot/main.py ADDED
@@ -0,0 +1,104 @@
1
+ import matplotlib.pyplot as plt
2
+ from matplotlib.axes import Axes
3
+ from matplotlib.path import Path
4
+ import matplotlib.patches as patches
5
+ from matplotlib.patches import PathPatch
6
+
7
+ import numpy as np
8
+
9
+ from narwhals.typing import IntoDataFrame
10
+
11
+ from bumplot.bezier import bezier_curve
12
+ from bumplot._utils import _get_first_n_colors, _ranked_df
13
+
14
+
15
+ def bumplot(
16
+ x: str,
17
+ y_columns: list[str],
18
+ data: IntoDataFrame,
19
+ curve_force: float = 1,
20
+ invert_y_axis: bool = True,
21
+ colors: list | None = None,
22
+ plot_kwargs: dict | None = None,
23
+ scatter_kwargs: dict | None = None,
24
+ ax: Axes | None = None,
25
+ ) -> Axes:
26
+ """
27
+ Creates bump plot, or bump chart, from multiple numerical
28
+ columns.
29
+
30
+ It requires the data to be in wide format (e.g., one column
31
+ per line you want to plot).
32
+
33
+ Args:
34
+ x: colname of the x-axis variable
35
+ y_columns: colnames of the y-axis variables
36
+ data: A dataframe
37
+ curve_force: Smoothing factor controlling curve tightness. Higher
38
+ values increase curvature by moving control points further away
39
+ from the anchors.
40
+ invert_y_axis: Whether to invert y axis
41
+ colors: An optional list of colors
42
+ plot_kwargs: Additional arguments passed to `patches.PathPatch()`
43
+ scatter_kwargs: Additional arguments passed to `scatter()`
44
+ ax: The matplotlib Axes used. Default to `plt.gca()`
45
+
46
+ Returns:
47
+ The matplotlib Axes with the bump plot
48
+ """
49
+ if ax is None:
50
+ ax: Axes = plt.gca()
51
+
52
+ default_plot_kwargs = {"facecolor": "none", "lw": 2}
53
+ if plot_kwargs is None:
54
+ plot_kwargs: dict = {}
55
+ default_plot_kwargs.update(plot_kwargs)
56
+
57
+ if scatter_kwargs is None:
58
+ scatter_kwargs: dict = {}
59
+
60
+ if colors is None:
61
+ colors: list[str] = _get_first_n_colors(n=len(y_columns))
62
+ else:
63
+ assert len(y_columns) <= len(colors), (
64
+ f"Not enough colors, expected <={len(y_columns)}, found {len(colors)}"
65
+ )
66
+
67
+ ranked: IntoDataFrame = _ranked_df(data, x=x, y_columns=y_columns)
68
+ x_values_raw: np.ndarray = np.ravel(ranked.select(x).to_numpy())
69
+
70
+ if np.issubdtype(x_values_raw.dtype, np.number):
71
+ x_values = x_values_raw
72
+ x_labels = x_values_raw
73
+ else:
74
+ uniques = list(dict.fromkeys(x_values_raw)) # preserves order
75
+ mapping = {val: i for i, val in enumerate(uniques)}
76
+ x_values = np.array([mapping[val] for val in x_values_raw], dtype=int)
77
+ x_labels = x_values_raw
78
+
79
+ for i, col in enumerate(y_columns):
80
+ y_values: np.ndarray = np.ravel(ranked.select(col).to_numpy())
81
+ vertices, codes = bezier_curve(
82
+ x=x_values,
83
+ y=y_values,
84
+ force=curve_force,
85
+ )
86
+
87
+ path: Path = Path(vertices=vertices, codes=codes)
88
+ patch: PathPatch = patches.PathPatch(
89
+ path=path,
90
+ edgecolor=colors[i],
91
+ **default_plot_kwargs,
92
+ )
93
+ ax.add_patch(patch)
94
+ ax.scatter(x_values, y_values, color=colors[i], label=col, **scatter_kwargs)
95
+
96
+ ticks: list[int] = list(range(1, len(y_columns) + 1))
97
+ if invert_y_axis:
98
+ ax.invert_yaxis()
99
+ else:
100
+ ticks: list[int] = list(reversed(ticks))
101
+ ax.set_yticks(ticks=ticks)
102
+ ax.set_xticks(ticks=np.unique(x_values), labels=np.unique(x_labels))
103
+
104
+ return ax
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: bumplot
3
+ Version: 0.1.0
4
+ Summary: Easily create and customize bump charts in Python
5
+ Author-email: Joseph Barbier <joseph.barbierdarnal@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://y-sunflower.github.io/bumplot/
8
+ Project-URL: Issues, https://github.com/y-sunflower/bumplot/issues
9
+ Project-URL: Documentation, https://y-sunflower.github.io/bumplot/
10
+ Project-URL: Repository, https://github.com/y-sunflower/bumplot
11
+ Keywords: bump,bump plot,bump charts,matplotlib,data,visualization
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Development Status :: 4 - Beta
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: matplotlib>=3.9.4
19
+ Requires-Dist: narwhals>=2.0.0
20
+ Dynamic: license-file
21
+
22
+
23
+
24
+ <!-- Automatically generated, uses README.qmd to modify README.md -->
25
+
26
+ # `bumplot`: easily create and customize bump charts in Python
27
+
28
+ <img src="https://github.com/JosephBARBIERDARNAL/static/blob/main/python-libs/bumplot/image.png?raw=true" alt="bumplot logo" align="right" width="180px"/>
29
+
30
+ `bumplot` is a small Python package made to facilitate the creation of
31
+ **bump charts** using matplotlib and Bézier curves. It has high
32
+ customization capabilities too!
33
+
34
+ Bump charts are useful when the focus is on comparing **relative
35
+ rankings**—who is ahead of whom—rather than the exact magnitude of the
36
+ differences.
37
+
38
+ Check out the [online
39
+ documentation](https://y-sunflower.github.io/bumplot/)
40
+
41
+ <br> <br>
42
+
43
+ ## Get started
44
+
45
+ ``` python
46
+ import matplotlib.pyplot as plt
47
+ import pandas as pd
48
+
49
+ from bumplot import bumplot
50
+
51
+ data = pd.DataFrame(
52
+ {
53
+ "x": [2020, 2021, 2022, 2023],
54
+ "A": [10, 50, 20, 80],
55
+ "B": [40, 30, 60, 10],
56
+ "C": [90, 20, 70, 40],
57
+ }
58
+ )
59
+ x = "x"
60
+ y_columns = ["A", "B", "C"]
61
+
62
+ fig, ax = plt.subplots(figsize=(8, 4))
63
+ bumplot(
64
+ x=x,
65
+ y_columns=y_columns,
66
+ data=data,
67
+ curve_force=0.5,
68
+ plot_kwargs={"lw": 4},
69
+ scatter_kwargs={"s": 150, "ec": "black", "lw": 2},
70
+ colors=["#ffbe0b", "#ff006e", "#3a86ff"],
71
+ )
72
+ ax.legend()
73
+ ax.spines[["top", "right", "left", "bottom"]].set_visible(False)
74
+ ax.grid(alpha=0.4)
75
+ ```
76
+
77
+ ![](README_files/figure-commonmark/cell-2-output-1.png)
78
+
79
+ [See more examples](https://y-sunflower.github.io/bumplot/examples/)
80
+
81
+ <br> <br>
82
+
83
+ ## Installation
84
+
85
+ pip install bumplot
@@ -0,0 +1,9 @@
1
+ bumplot/__init__.py,sha256=iAae8sD9-zkDT15T3hTBltnJnmC7InHXX8tnRlTnC6Y,71
2
+ bumplot/_utils.py,sha256=bploOlyOu2GT1QoA0V0T1dOYRfA59fbyCieOBaJQkFc,789
3
+ bumplot/bezier.py,sha256=-GiiZOu8lNH3yKBPBri5C3KInxm17nYB5guAFP8Qb8Q,1253
4
+ bumplot/main.py,sha256=92T6xqJG6hh4QqIYXwW5jmjo1E4VvB78O6iWSahvFGM,3350
5
+ bumplot-0.1.0.dist-info/licenses/LICENSE,sha256=K6JmhrEwtKtERXknPaQzAyliC-ZgMmSxwSjuwwsuCEw,1061
6
+ bumplot-0.1.0.dist-info/METADATA,sha256=Xpf4U0RmuQmD_yR8IFHayKtjXDrrHtiunk822ZXJzGg,2380
7
+ bumplot-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
+ bumplot-0.1.0.dist-info/top_level.txt,sha256=Uwy_9Tcw4jpd4cZNoBd1gTgSLj6Jm_vJQFIsASctRag,8
9
+ bumplot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Year Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ bumplot