"""
Plots the views computed by :class:`data_cube.DataCube`.
"""
import io
import os
from typing import Dict, List, Optional
import pandas
from ._helper import string_sig
[docs]
class CubePlot:
"""
Creates a plot.
:param df: dataframe
:param kind: kind of graph to plot, bar, barh, line
:param split: draw a graph per line in the dataframe
:param timeseries: this assumes the time is one level of the columns,
this argument indices the level name
It defines a graph. Usually *bar* or *barh* is used to
compare experiments for every metric, a subplot by metric.
.. code-block:: python
CubePlot(df, kind="barh", orientation="row", split=True)
*line* is usually used to plot timeseries showing the
evolution of metrics over time.
.. code-block:: python
CubePlot(
df,
kind="line",
orientation="row",
split=True,
timeseries="time",
)
"""
KINDS = {"bar", "barh", "line"}
[docs]
@classmethod
def group_columns(cls, columns: List[str], sep: str = "/", depth: int = 2) -> List[List[str]]:
"""Groups columns to have nice display."""
res: Dict[str, List[str]] = {}
for c in columns:
p = c.split("/")
k = "/".join(p[:depth])
if k not in res:
res[k] = []
res[k].append(c)
new_res: Dict[str, List[str]] = {}
for k, v in res.items():
if len(v) >= 3:
new_res[k] = v
else:
if "0" not in new_res:
new_res["0"] = []
new_res["0"].extend(v)
groups: List[List[str]] = [sorted(v) for k, v in sorted(new_res.items())]
if depth <= 1:
return groups
new_groups: List[List[str]] = []
for v in groups:
if len(v) >= 6:
new_groups.extend(cls.group_columns(v, depth=1, sep=sep))
else:
new_groups.append(v)
return new_groups
def __init__(
self,
df: pandas.DataFrame,
kind: str = "bar",
orientation="col",
split: bool = True,
timeseries: Optional[str] = None,
):
assert (
not timeseries or timeseries in df.columns.names
), f"Level {timeseries!r} is not part of the columns levels {df.columns.names}"
assert (
kind in self.__class__.KINDS
), f"Unexpected kind={kind!r} not in {self.__class__.KINDS}"
assert split, f"split={split} not implemented"
assert (
not timeseries or orientation == "row"
), f"orientation={orientation!r} must be 'row' for timeseries"
self.df = df.copy()
self.kind = kind
self.orientation = orientation
self.split = split
self.timeseries = timeseries
if timeseries:
if isinstance(self.df.columns, pandas.MultiIndex):
index_time = list(self.df.columns.names).index(self.timeseries)
def _drop(t, i=index_time):
return (*t[:i], *t[i + 1 :])
self.df.columns = pandas.MultiIndex.from_tuples(
[("/".join(map(str, _drop(i))), i[index_time]) for i in self.df.columns],
names=["metric", timeseries],
)
else:
if isinstance(self.df.columns, pandas.MultiIndex):
self.df.columns = ["/".join(map(str, i)) for i in self.df.columns]
if isinstance(self.df.index, pandas.MultiIndex):
self.df.index = ["/".join(map(str, i)) for i in self.df.index]
def __repr__(self) -> str:
"usual"
return string_sig(self) # type: ignore[arg-type]
[docs]
def to_images(
self, verbose: int = 0, merge: bool = True, title_suffix: Optional[str] = None
) -> List[bytes]:
"""
Converts data into plots and images.
:param verbose: verbosity
:param merge: returns all graphs in a single image (True)
or an image for every graph (False)
:param title_suffix: suffix for the title of every graph
:return: list of binary images (format PNG)
"""
if self.kind in ("barh", "bar"):
return self._to_images_bar(verbose=verbose, merge=merge, title_suffix=title_suffix)
if self.kind == "line":
return self._to_images_line(verbose=verbose, merge=merge, title_suffix=title_suffix)
raise AssertionError(f"self.kind={self.kind!r} not implemented")
@classmethod
def _make_loop(cls, ensemble, verbose):
if verbose: # pragma: no cover
try:
from tqdm import tqdm
loop = tqdm(ensemble)
except ImportError:
loop = ensemble
else:
loop = ensemble
return loop
def _to_images_bar(
self, verbose: int = 0, merge: bool = True, title_suffix: Optional[str] = None
) -> List[bytes]:
"""
Environment variable ``FIGSIZEH`` can be set to increase the
graph height. Default is 1.0.
"""
assert merge, f"merge={merge} not implemented yet"
import matplotlib.pyplot as plt # type: ignore
df = self.df.T if self.orientation == "row" else self.df
title_suffix = f"\n{title_suffix}" if title_suffix else ""
n_cols = 3
nn = df.shape[1] // n_cols
nn += int(df.shape[1] % n_cols != 0)
ratio = float(os.environ.get("FIGSIZEH", "1"))
figsize = (6 * n_cols, nn * (2.5 + df.shape[0] / 15) * ratio)
fig, axs = plt.subplots(nn, n_cols, figsize=figsize)
pos = 0
imgs = []
for c in self._make_loop(df.columns, verbose):
ax = axs[pos // n_cols, pos % n_cols]
(
df[c].plot.barh(title=f"{c}{title_suffix}", ax=ax)
if self.kind == "barh"
else df[c].plot.bar(title=f"{c}{title_suffix}", ax=ax)
)
ax.tick_params(axis="both", which="major", labelsize=8)
ax.grid(True)
pos += 1 # noqa: SIM113
fig.tight_layout()
imgdata = io.BytesIO()
fig.savefig(imgdata, format="png")
imgs.append(imgdata.getvalue())
plt.close()
return imgs
def _to_images_line(
self, verbose: int = 0, merge: bool = True, title_suffix: Optional[str] = None
) -> List[bytes]:
assert merge, f"merge={merge} not implemented yet"
assert (
self.orientation == "row"
), f"self.orientation={self.orientation!r} not implemented for this kind of graph."
def rotate_align(ax, angle=15, align="right"):
for label in ax.get_xticklabels():
label.set_rotation(angle)
label.set_horizontalalignment(align)
ax.tick_params(axis="both", which="major", labelsize=8)
ax.grid(True)
ax.legend()
ax.tick_params(labelleft=True)
return ax
import matplotlib.pyplot as plt # type: ignore
df = self.df.T
confs = list(df.unstack(self.timeseries).index)
groups = self.group_columns(confs)
n_cols = len(groups)
title_suffix = f"\n{title_suffix}" if title_suffix else ""
ratio = float(os.environ.get("FIGSIZEH", "1"))
figsize = (5 * n_cols, max(len(g) for g in groups) * (2 + df.shape[1] / 2) * ratio)
fig, axs = plt.subplots(
df.shape[1],
n_cols,
figsize=figsize,
sharex=True,
sharey="row" if n_cols > 1 else False,
)
imgs = []
row = 0
for c in self._make_loop(df.columns, verbose):
dfc = df[[c]]
dfc = dfc.unstack(self.timeseries).T.droplevel(0)
if n_cols == 1:
dfc.plot(title=f"{c}{title_suffix}", ax=axs[row], linewidth=3)
axs[row].grid(True)
rotate_align(axs[row])
else:
x = list(range(dfc.shape[0]))
ticks = list(dfc.index)
for ii, group in enumerate(groups):
ddd = dfc.loc[:, group].copy()
axs[row, ii].set_xticks(x)
axs[row, ii].set_xticklabels(ticks)
# This is very slow
# ddd.plot(ax=axs[row, ii],linewidth=3)
for jj in range(ddd.shape[1]):
# pyrefly: ignore[bad-index]
axs[row, ii].plot(x, ddd.iloc[:, jj], lw=3, label=ddd.columns[jj])
axs[row, ii].set_title(f"{c}{title_suffix}")
rotate_align(axs[row, ii])
row += 1 # noqa: SIM113
fig.tight_layout()
imgdata = io.BytesIO()
fig.savefig(imgdata, format="png")
imgs.append(imgdata.getvalue())
plt.close()
return imgs