-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathlines.py
More file actions
214 lines (180 loc) · 5.76 KB
/
Copy pathlines.py
File metadata and controls
214 lines (180 loc) · 5.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""Line chart primitives styled to match the shared analytics theme."""
from __future__ import annotations
from pathlib import Path
import matplotlib.ticker as ticker
import pandas as pd
from hiero_analytics.config.charts import FIGURE_BACKGROUND_COLOR, PRIMARY_PALETTE
from .base import create_figure, finalize_chart, prepare_dataframe
from .primitives import annotate_endpoint_badge, build_palette, format_chart_value
def plot_line(
df: pd.DataFrame,
x_col: str,
y_col: str,
title: str,
output_path: Path,
rotate_x: int | None = None,
) -> None:
"""Plot a single-series line chart."""
df = prepare_dataframe(df, x_col, y_col)
data = df.sort_values(x_col).copy()
# Ensure numeric x-axis values
data[x_col] = pd.to_numeric(data[x_col], errors="coerce")
data = data.dropna(subset=[x_col])
if data.empty:
raise ValueError("No valid numeric x-axis values")
fig, ax = create_figure()
ax.plot(
data[x_col],
data[y_col],
marker="o",
color=PRIMARY_PALETTE[2],
linewidth=2.6,
markersize=7,
markeredgecolor=FIGURE_BACKGROUND_COLOR,
markeredgewidth=2,
solid_capstyle="round",
zorder=3,
)
ax.fill_between(
data[x_col],
data[y_col],
0,
color=PRIMARY_PALETTE[2],
alpha=0.08,
zorder=2,
)
annotate_endpoint_badge(
ax,
x=float(data[x_col].iloc[-1]),
y=float(data[y_col].iloc[-1]),
text=f"{y_col} {format_chart_value(float(data[y_col].iloc[-1]))}",
color=PRIMARY_PALETTE[2],
y_offset=-4,
)
ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
ax.yaxis.set_major_locator(ticker.MaxNLocator(integer=True))
ax.set_ylim(bottom=0)
ax.set_xlim(float(data[x_col].min()) - 0.15, float(data[x_col].max()) + 0.45)
ax.margins(x=0.03, y=0.16)
finalize_chart(
fig=fig,
ax=ax,
title=title,
xlabel=x_col,
ylabel=y_col,
output_path=output_path,
rotate_x=rotate_x,
grid_axis="y",
)
def plot_multiline(
df: pd.DataFrame,
x_col: str,
y_col: str,
group_col: str,
title: str,
output_path: Path,
colors: dict[str, str] | None = None,
rotate_x: int | None = None,
) -> None:
"""
Plot a multi-series line chart grouped by a column.
Parameters
----------
df : pd.DataFrame
Input dataset.
x_col : str
Column used for x-axis.
y_col : str
Column used for y values.
group_col : str
Column defining the separate series.
title : str
Chart title.
output_path : Path
File path where the chart image will be saved.
colors : dict[str, str] | None
Optional mapping of series label -> color.
rotate_x : int | None
Optional x-axis label rotation.
"""
df = prepare_dataframe(df, x_col, y_col, group_col).copy()
pivot = df.pivot_table(index=x_col, columns=group_col, values=y_col, aggfunc="sum").sort_index()
if pivot.empty:
raise ValueError("Pivot produced an empty dataset")
pivot.index = pd.to_numeric(pivot.index, errors="coerce")
pivot = pivot.dropna(axis=0, how="all")
pivot = pivot[~pivot.index.isna()]
if pivot.empty:
raise ValueError("No valid numeric x-axis values")
fig, ax = create_figure()
palette = build_palette(len(pivot.columns))
endpoint_offsets = [-14, 0, 14, 28, 42]
for index, column in enumerate(pivot.columns):
color = colors.get(column) if colors else palette[index]
is_total = str(column).lower() == "total"
series = pivot[column].dropna()
ax.plot(
series.index,
series,
marker="o",
label=str(column),
color=color,
linewidth=3 if is_total else 2.4,
markersize=7,
markeredgecolor=FIGURE_BACKGROUND_COLOR,
markeredgewidth=2,
solid_capstyle="round",
zorder=3,
)
if is_total:
# The total line gets a subtle area fill so it reads as the main
# trend without overpowering the other series.
ax.fill_between(
series.index,
series,
0,
color=color,
alpha=0.08,
zorder=2,
)
annotate_endpoint_badge(
ax,
x=float(series.index[-1]),
y=float(series.iloc[-1]),
text=f"{column} {format_chart_value(float(series.iloc[-1]))}",
color=color,
y_offset=endpoint_offsets[index % len(endpoint_offsets)],
)
ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
ax.yaxis.set_major_locator(ticker.MaxNLocator(integer=True))
ax.set_ylim(bottom=0)
ax.set_xlim(float(pivot.index.min()) - 0.15, float(pivot.index.max()) + 0.45)
ax.margins(x=0.03, y=0.16)
legend_count = len(pivot.columns)
## Prefer Bottom legend, Right legend only when many items
if legend_count > 6:
legend_loc = "upper left"
legend_bbox_to_anchor = (1.02, 1.0)
legend_ncol = 1
layout_rect = (0, 0, 0.85, 1.0)
else:
legend_loc = "lower center"
legend_bbox_to_anchor = (0.5, -0.18)
legend_ncol = min(legend_count, 4)
layout_rect = (0, 0.12, 1.0, 1.0)
finalize_chart(
fig=fig,
ax=ax,
title=title,
xlabel=x_col,
ylabel=y_col,
output_path=output_path,
legend=True,
rotate_x=rotate_x,
grid_axis="y",
legend_loc=legend_loc,
legend_bbox_to_anchor=legend_bbox_to_anchor,
legend_ncol=legend_ncol,
legend_kwargs={"borderaxespad": 0.0},
layout_rect=layout_rect,
)