Skip to content

facetbars.py

ESM grouped barcharts.

ESMGroupedBarChart

A class that produces multiple bar charts in subplots.

Parameters:

Name Type Description Default
df pandas.DataFrame

Metric data frame complying with the evaluation data model.

required
cfg types.SimpleNamespace

Plotly configuration object with styling and export settings.

required
Source code in evals/plots/facetbars.py
 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
class ESMGroupedBarChart:
    """
    A class that produces multiple bar charts in subplots.

    Parameters
    ----------
    df
        Metric data frame complying with the evaluation data model.
    cfg
        Plotly configuration object with styling and export settings.
    """

    def __init__(self, df: pd.DataFrame, cfg: SimpleNamespace) -> None:
        self._df = df
        self.cfg = cfg
        self.unit = self.cfg.unit or df.attrs["unit"]
        self.metric_name = df.attrs["name"]
        self.location = self._df.index.unique(DataModel.LOCATION)[0]
        self.col_values = self._df.columns[0]

        ncols = len(self.df[DataModel.BUS_CARRIER].unique())
        ncols = ncols or 1
        column_widths = [0.85 / ncols] * ncols
        self.fig = make_subplots(
            rows=1, cols=ncols, shared_yaxes=True, column_widths=column_widths
        )

    @cached_property
    def df(self) -> pd.DataFrame:
        """
        Plot data formatted for grouped bar charts.

        Returns
        -------
        :
            The formatted data for creating bar charts.
        """
        df = apply_cutoff(self._df, limit=self.cfg.cutoff, drop=False)
        df = df.reset_index()

        fill_values = product(
            df[DataModel.YEAR].unique(),
            df[DataModel.LOCATION].unique(),
            df[DataModel.CARRIER].unique(),
            df[DataModel.BUS_CARRIER].unique(),
        )
        df_fill = pd.DataFrame(columns=DataModel.YEAR_IDX_NAMES, data=fill_values)
        df_fill[self.col_values] = np.nan
        df = pd.concat([df, df_fill], ignore_index=True)

        df_list = []
        for _, df_sector in df.groupby(self.cfg.facet_column, sort=True):
            sorted_sector = custom_sort(
                df_sector,
                by=self.cfg.plot_category,
                values=self.cfg.category_orders,
                ascending=True,
            )
            df_list.append(sorted_sector)
        df = pd.concat(df_list)

        df = df.dropna(how="all", subset=self.col_values)
        df["display_value"] = df[self.col_values].apply(prettify_number)
        return df

    def plot(self) -> None:
        """Create the bar chart."""
        title = self.cfg.title.format(location=self.location, unit=self.unit)
        if empty_input(self._df) or self.df[self.col_values].isna().all():
            self.fig = empty_figure(title)
            return

        pattern = {
            col: self.cfg.pattern.get(col, "")
            for col in self.df[self.cfg.plot_category].unique()
        }

        self.fig = px.bar(
            self.df,
            x=self.cfg.plot_xaxis,
            y=self.col_values,
            facet_col=self.cfg.facet_column,
            facet_col_spacing=0.04,
            pattern_shape=self.cfg.plot_category,
            pattern_shape_map=pattern,
            color=self.cfg.plot_category,
            color_discrete_map=self.cfg.colors,
            text=self.cfg.facet_column,
            title=title,
            custom_data=[self.cfg.plot_category, "display_value"],
        )

        self.fig.for_each_xaxis(self._rename_xaxis)

        total_renderer = TotalSumRenderer(
            col_values=self.col_values,
            plot_xaxis=self.cfg.plot_xaxis,
            unit=self.unit,
        )
        total_renderer.add_subplot_traces(self.fig, self.df, self.cfg.facet_column)

        self.fig.update_annotations(text="")

        layout_styler = LayoutStyler(self.cfg)
        bar_styler = BarTraceStyler(width=0.8)

        layout_styler.set_base_layout(self.fig)
        bar_styler.apply(self.fig, self.unit)
        layout_styler.style_title_and_legend_and_xaxis_label(self.fig)
        layout_styler.append_footnotes(self.fig)

        self.fig.update_xaxes(fixedrange=True)
        self.fig.update_yaxes(fixedrange=True)
        self.fig.for_each_xaxis(self._style_inner_xaxis_labels)

    def _rename_xaxis(self, xaxis: go.layout.XAxis) -> None:
        """
        Update the xaxis labels.

        Parameters
        ----------
        xaxis
            The subplot xaxis (a dictionary).
        """
        layout = self.fig["layout"]
        idx = xaxis["anchor"].lstrip("y")
        for data in self.fig["data"]:
            if data["xaxis"] == f"x{idx}":
                sector = data["text"][0]
                layout[f"xaxis{idx}"]["title"]["text"] = f"<b>{sector}"
                break

    def _style_inner_xaxis_labels(self, xaxis: go.layout.XAxis) -> None:
        """
        Set the font size for inner xaxis labels.

        Parameters
        ----------
        xaxis
            The subplot xaxis (a dictionary-like object).
        """
        xaxis.update(
            tickfont_size=self.cfg.xaxis_font_size,
            categoryorder="category ascending",
        )

df cached property

Plot data formatted for grouped bar charts.

Returns:

Type Description
pandas.DataFrame

The formatted data for creating bar charts.

plot()

Create the bar chart.

Source code in evals/plots/facetbars.py
 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
def plot(self) -> None:
    """Create the bar chart."""
    title = self.cfg.title.format(location=self.location, unit=self.unit)
    if empty_input(self._df) or self.df[self.col_values].isna().all():
        self.fig = empty_figure(title)
        return

    pattern = {
        col: self.cfg.pattern.get(col, "")
        for col in self.df[self.cfg.plot_category].unique()
    }

    self.fig = px.bar(
        self.df,
        x=self.cfg.plot_xaxis,
        y=self.col_values,
        facet_col=self.cfg.facet_column,
        facet_col_spacing=0.04,
        pattern_shape=self.cfg.plot_category,
        pattern_shape_map=pattern,
        color=self.cfg.plot_category,
        color_discrete_map=self.cfg.colors,
        text=self.cfg.facet_column,
        title=title,
        custom_data=[self.cfg.plot_category, "display_value"],
    )

    self.fig.for_each_xaxis(self._rename_xaxis)

    total_renderer = TotalSumRenderer(
        col_values=self.col_values,
        plot_xaxis=self.cfg.plot_xaxis,
        unit=self.unit,
    )
    total_renderer.add_subplot_traces(self.fig, self.df, self.cfg.facet_column)

    self.fig.update_annotations(text="")

    layout_styler = LayoutStyler(self.cfg)
    bar_styler = BarTraceStyler(width=0.8)

    layout_styler.set_base_layout(self.fig)
    bar_styler.apply(self.fig, self.unit)
    layout_styler.style_title_and_legend_and_xaxis_label(self.fig)
    layout_styler.append_footnotes(self.fig)

    self.fig.update_xaxes(fixedrange=True)
    self.fig.update_yaxes(fixedrange=True)
    self.fig.for_each_xaxis(self._style_inner_xaxis_labels)