I started using plotly. It renders a nice looking chart by default and interactive. With some efforts, one can return json in the server to render it via js.
Another benefit is that charts can be merged. It’s very useful in rendering two different lines, e.g., trainig data + test data in a single chart. For example, this is how one can draw a data frame as a line.
def line_for_df(
df: pl.DataFrame,
x_col: str,
y_col: str,
*,
color: str | None = None,
name: str | None = None,
) -> Figure:
fig = px.line(df, x=x_col, y=y_col)
if color:
fig.update_traces(line_color=color)
if name:
fig.update_traces(name=name)
return fig
After drawing two figures, one can merge them.
def merge_lines(figs: list[Figure]) -> Figure:
merged_fig = figs[0]
for fig in figs[1:]:
for trace in fig.data:
merged_fig.add_trace(trace)
merged_fig.update_layout(
showlegend=True,
legend=dict(orientation="h", yanchor="bottom", y=1.0, xanchor="center", x=0.5),
)
merged_fig.update_traces(showlegend=True)
return merged_fig
For example, this is how I render training and test data in a single chart.
def line_for_split(
split: Split,
x_col: str,
y_col: str,
) -> Figure:
train = split.train.X.rename({y_col: "train"})
test = split.test.X.rename({y_col: "test"})
fig1 = line_for_df(train, x_col, "train", color="blue", name="train")
fig2 = line_for_df(test, x_col, "test", color="red", name="test")
fig = merge_lines([fig1, fig2])
return fig
It’s pretty amazing since I don’t need to merge the two dfs to render them in a single chart.