Module: heat_map_plot
Expand source code
# Copyright (C) 2023-present The Project Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from dataclasses import dataclass
from typing import List
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from cl.runtime import Context
from cl.runtime.plots.heat_map_plot_style import HeatMapPlotStyle
from cl.runtime.plots.matplotlib_plot import MatplotlibPlot
from cl.runtime.plots.matplotlib_util import MatplotlibUtil
from cl.runtime.plots.plot import Plot
from cl.runtime.records.dataclasses_extensions import field
@dataclass(slots=True, kw_only=True)
class HeatMapPlot(MatplotlibPlot):
"""Heat map visualization."""
title: str = field()
"""Plot title."""
row_labels: List[str] = field()
"""Row label for each cell in the same order of cells as other fields."""
col_labels: List[str] = field()
"""Column label for each cell in the same order of cells as other fields."""
received_values: List[str] = field()
"""Received value for each cell in the same order of cells as other fields."""
expected_values: List[str] = field()
"""Expected (correct) value for each cell in the same order of cells as other fields."""
x_label: str = field()
"""x-axis label."""
y_label: str = field()
"""y-axis label."""
def _create_figure(self) -> plt.Figure:
# Load style object or create with default settings if not specified
style = self._load_style()
theme = self._get_pyplot_theme(style=style)
received_df, expected_df = (
pd.DataFrame.from_records([values, self.col_labels, self.row_labels], index=["Value", "Col", "Row"])
.T.pivot_table(index="Row", columns="Col", values="Value", sort=False)
.astype(float)
for values in [self.received_values, self.expected_values]
)
data = (received_df - expected_df).abs()
with plt.style.context(theme):
fig, axes = plt.subplots()
cmap = LinearSegmentedColormap.from_list("rg", ["g", "y", "r"], N=256)
im = MatplotlibUtil.heatmap(data.values, data.index.tolist(), data.columns.tolist(), ax=axes, cmap=cmap)
# Set figure and axes labels
axes.set_xlabel(self.x_label)
axes.set_ylabel(self.y_label)
axes.set_title(self.title)
fig.tight_layout()
return fig
def _load_style(self) -> HeatMapPlotStyle:
"""Load style object or create with default settings if not specified."""
style = Context.current().load_one(HeatMapPlotStyle, self.style, is_key_optional=True)
if style is None:
# Use default values if not found
style = HeatMapPlotStyle(plot_style_id="Default")
style.init_all()
return style
Classes
class HeatMapPlot (*, plot_id: str = None, style: PlotStyleKey | None = None, title: str = None, row_labels: List[str] = None, col_labels: List[str] = None, received_values: List[str] = None, expected_values: List[str] = None, x_label: str = None, y_label: str = None)
-
Heat map visualization.
Expand source code
@dataclass(slots=True, kw_only=True) class HeatMapPlot(MatplotlibPlot): """Heat map visualization.""" title: str = field() """Plot title.""" row_labels: List[str] = field() """Row label for each cell in the same order of cells as other fields.""" col_labels: List[str] = field() """Column label for each cell in the same order of cells as other fields.""" received_values: List[str] = field() """Received value for each cell in the same order of cells as other fields.""" expected_values: List[str] = field() """Expected (correct) value for each cell in the same order of cells as other fields.""" x_label: str = field() """x-axis label.""" y_label: str = field() """y-axis label.""" def _create_figure(self) -> plt.Figure: # Load style object or create with default settings if not specified style = self._load_style() theme = self._get_pyplot_theme(style=style) received_df, expected_df = ( pd.DataFrame.from_records([values, self.col_labels, self.row_labels], index=["Value", "Col", "Row"]) .T.pivot_table(index="Row", columns="Col", values="Value", sort=False) .astype(float) for values in [self.received_values, self.expected_values] ) data = (received_df - expected_df).abs() with plt.style.context(theme): fig, axes = plt.subplots() cmap = LinearSegmentedColormap.from_list("rg", ["g", "y", "r"], N=256) im = MatplotlibUtil.heatmap(data.values, data.index.tolist(), data.columns.tolist(), ax=axes, cmap=cmap) # Set figure and axes labels axes.set_xlabel(self.x_label) axes.set_ylabel(self.y_label) axes.set_title(self.title) fig.tight_layout() return fig def _load_style(self) -> HeatMapPlotStyle: """Load style object or create with default settings if not specified.""" style = Context.current().load_one(HeatMapPlotStyle, self.style, is_key_optional=True) if style is None: # Use default values if not found style = HeatMapPlotStyle(plot_style_id="Default") style.init_all() return style
Ancestors
- MatplotlibPlot
- Plot
- PlotKey
- KeyMixin
- RecordMixin
- abc.ABC
- typing.Generic
Static methods
def get_key_type() -> Type
-
Inherited from:
MatplotlibPlot
.get_key_type
Return key type even when called from a record.
Fields
var col_labels -> List[str]
-
Column label for each cell in the same order of cells as other fields.
var expected_values -> List[str]
-
Expected (correct) value for each cell in the same order of cells as other fields.
var plot_id -> str
-
Inherited from:
MatplotlibPlot
.plot_id
Unique plot identifier.
var received_values -> List[str]
-
Received value for each cell in the same order of cells as other fields.
var row_labels -> List[str]
-
Row label for each cell in the same order of cells as other fields.
var style -> PlotStyleKey | None
-
Inherited from:
MatplotlibPlot
.style
Color and layout options.
var title -> str
-
Plot title.
var x_label -> str
-
x-axis label.
var y_label -> str
-
y-axis label.
Methods
def get_key(self) -> PlotKey
-
Inherited from:
MatplotlibPlot
.get_key
Return a new key object whose fields populated from self, do not return self.
def get_view(self) -> View
-
Inherited from:
MatplotlibPlot
.get_view
Return a view object for the plot, implement using ‘create_figure’ method.
def init_all(self) -> None
-
Inherited from:
MatplotlibPlot
.init_all
Invoke ‘init’ for each class in the order from base to derived, then validate against schema.
def save_png(self) -> None
-
Inherited from:
MatplotlibPlot
.save_png
Save in png format to ‘base_dir/plot_id.png’, implement using ‘create_figure’ method.