# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05_utils.plot.ipynb (unless otherwise specified).

__all__ = ['plot2series', 'add_value_labels', 'plot_yearly_gain']

# Cell
from ..imports import *
from .pandas_hacks import *

# Cell
@delegates(plt.subplots)
def plot2series(s1: Series, s2: Series, names:Optional[str]=None, y_label='y', **kwargs):
    "Plots 2 Series against each other"
    fig, ax = plt.subplots(**kwargs)
    pd.concat([s1, s2], axis=1).plot(ax=ax)
    names = ifnone(names, [s1.name, s2.name])
    ax.legend(names)
    ax.set_ylabel(y_label)
    return ax

# Cell
def add_value_labels(ax, labels=None, spacing=5):
    """Add labels to the end of each bar in a bar chart.

    Arguments:
        ax (matplotlib.axes.Axes): The matplotlib object containing the axes
            of the plot to annotate.
        spacing (int): The distance between the labels and the bars.
    """

    # For each bar: Place a label
    labels = ifnone(labels, [None]*len(ax.patches))
    for rect, label in zip(ax.patches, labels):
        # Get X and Y placement of label from rect.
        y_value = rect.get_height()
        x_value = rect.get_x() + rect.get_width() / 2

        # Number of points between bar and label. Change to your liking.
        space = spacing
        # Vertical alignment for positive values
        va = 'bottom'

        # If value of bar is negative: Place label below bar
        if y_value < 0:
            # Invert space to place label below
            space *= -1
            # Vertically align label at top
            va = 'top'

        # Use Y value as label and format number with one decimal place
        label = "{:.1f}".format(ifnone(label, y_value))

        # Create annotation
        ax.annotate(
            label,                      # Use `label` as label
            (x_value, y_value),         # Place label at end of the bar
            xytext=(0, space),          # Vertically shift label by `space`
            textcoords="offset points", # Interpret `xytext` as offset in points
            ha='center',                # Horizontally center label
            va=va)                      # Vertically align label differently for
                                        # positive and negative values.
    return

# Cell
def plot_yearly_gain(s1: Series, s2: Series, labels=None):
    "Plot bar chart with gain percentage"
    labels = ifnone(labels, ['s1', 's2'])
    _, ax = plt.subplots(figsize=(12,5))
    (pd.concat([s1, s2-s1], axis=1,sort=False)
    .plot.bar(ax=ax, stacked=True, color=['blue', 'violet']))
    ax.set_title('Gain')
    ax.legend(labels)
    gain = 100*(s2/s1-1)
    add_value_labels(ax, gain, spacing=5)
    return