<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Collection of annotation routines for MatPlotLib

Created on Sat Oct 21 13:59:11 2017

@author: dan
"""

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import pandas as pd
import numpy as np

def _Data2Axes(d, ax):
    """Convert from data space to axes space
    """
    axis_to_data = ax.transAxes + ax.transData.inverted()
    data_to_axis = axis_to_data.inverted()
    return data_to_axis.transform(d)

def _gfa():
    """ Utility function to get first axes on the figure.
    """
    fig = plt.gcf()
    return fig.get_axes()[0]

def MonthFmt(ax):
    """Set the y-axis to months with names between tick marks

    Parameters
    ----------
    ax : Matplotlib axes
        axes to be formatted.
    """
    # Set up axis formatting
    # Format codes are at:
    # https://docs.python.org/3/library
    #             /datetime.html#strftime-and-strptime-behavior
    monthly = mdates.MonthLocator()
    monthFmt = mdates.DateFormatter('%b')
    blankFmt = mdates.DateFormatter(' ')
    bimonthly = mdates.DayLocator(15)

    ax.yaxis.set_major_locator(monthly)
    ax.yaxis.set_minor_locator(bimonthly)
    ax.yaxis.set_minor_formatter(monthFmt)
    ax.yaxis.set_major_formatter(blankFmt)

    ax.tick_params(axis='y', which='minor', color=(0,0,0,0))

def AddYAxis(ax, month=False, pad=None):
    """Adds y-axis that's a mirror of the y-axis on left.

    Parameters
    ----------
    ax : Axes
        Axes to be mirrored
    month : boolean default False
        Flag indicating that the axis has month labels, which must be handled
        differently.
    pad : int Default None
        Adjustment for location of labels. How far from the axis the right
        side of the label is since it is right-justified. If not supplied,
        a pretty good estimate is used.
    Returns
    -------
    pad : float
        Value of actually pad used. This can help as an adjustment starting
        point if the estimated value is not right.
    Notes
    -----
    1. Use this function just before the final fig.show() command. Anywhere
    else causes problems with plotting to the wrong axes.

    2. Padding tested on a Retina MacPowerbook. It might be off if another
    system is used.
    """
    ax2 = ax.twinx()
    ax2.grid(False) # is sitting on top of lines
    ax2.set_yticks(ax.get_yticks())
    ax2.set_ylim(ax.get_ylim())
    yax = ax.get_yaxis()
    yax2 = ax2.get_yaxis()
    if month:
        yax2.set_major_locator(yax.get_major_locator())
        yax2.set_minor_locator(yax.get_minor_locator())
        yax2.set_major_formatter(yax.get_major_formatter())
        yax2.set_minor_formatter(yax.get_minor_formatter())
    else:
        ts = ax2.get_yticklabels()
        [t.set_ha('right') for t in ts]
        if not pad:
            ax.figure.canvas.draw()
            rend = ax.figure.canvas.get_renderer()
            bboxes = yax.get_ticklabel_extents(rend)
            w = max(b.width for b in bboxes)
            # Value (2.8) tested with Mac Retina Display.
            # Might not work on other systems.
            if plt.get_backend().startswith('Mac'):
                pad = w/2.8 - 2
            else:
                pad = w/1.4 - 2
        yax2.set_tick_params(pad=pad)
    #fixes axis overlap in 'ggplot' style
    ax2.spines['right'].set_alpha(0)
    if month:
        ax2.tick_params(axis='y', which='minor', color=(0,0,0,0))
    else:
        ax.tick_params(axis='y', color=(0,0,0,0))
        ax2.tick_params(axis='y', color=(0,0,0,0))

    return pad

def Baseline(range):
    """Add baseline to current plot.

    Paramters
    ---------
    range : list<commit_msg>Add a % feature to AddYAxis<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Collection of annotation routines for MatPlotLib

Created on Sat Oct 21 13:59:11 2017

@author: dan
"""

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mtick
import datetime as dt
import pandas as pd
import numpy as np

def _Data2Axes(d, ax):
    """Convert from data space to axes space
    """
    axis_to_data = ax.transAxes + ax.transData.inverted()
    data_to_axis = axis_to_data.inverted()
    return data_to_axis.transform(d)

def _gfa():
    """ Utility function to get first axes on the figure.
    """
    fig = plt.gcf()
    return fig.get_axes()[0]

def MonthFmt(ax):
    """Set the y-axis to months with names between tick marks

    Parameters
    ----------
    ax : Matplotlib axes
        axes to be formatted.
    """
    # Set up axis formatting
    # Format codes are at:
    # https://docs.python.org/3/library
    #             /datetime.html#strftime-and-strptime-behavior
    monthly = mdates.MonthLocator()
    monthFmt = mdates.DateFormatter('%b')
    blankFmt = mdates.DateFormatter(' ')
    bimonthly = mdates.DayLocator(15)

    ax.yaxis.set_major_locator(monthly)
    ax.yaxis.set_minor_locator(bimonthly)
    ax.yaxis.set_minor_formatter(monthFmt)
    ax.yaxis.set_major_formatter(blankFmt)

    ax.tick_params(axis='y', which='minor', color=(0,0,0,0))

def AddYAxis(ax, month=False, pad=None, percent=None):
    """Adds y-axis that's a mirror of the y-axis on left.

    Parameters
    ----------
    ax : Axes
        Axes to be mirrored
    month : boolean default False
        Flag indicating that the axis has month labels, which must be handled
        differently.
    pad : int Default None
        Adjustment for location of labels. How far from the axis the right
        side of the label is since it is right-justified. If not supplied,
        a pretty good estimate is used.
    percent : int, float, or None default None
        Use if a percentate is desired on the right y-axis labels.
        ``percent=365`` to give percent of a year.

    Returns
    -------
    pad : float
        Value of actually pad used. This can help as an adjustment starting
        point if the estimated value is not right.
    Notes
    -----
    1. Use this function just before the final fig.show() command. Anywhere
    else causes problems with plotting to the wrong axes.

    2. Padding tested on a Retina MacPowerbook. It might be off if another
    system is used.
    """
    ax2 = ax.twinx()
    ax2.grid(False) # is sitting on top of lines
    ax2.set_yticks(ax.get_yticks())
    ax2.set_ylim(ax.get_ylim())
    yax = ax.get_yaxis()
    yax2 = ax2.get_yaxis()
    if month:
        yax2.set_major_locator(yax.get_major_locator())
        yax2.set_minor_locator(yax.get_minor_locator())
        yax2.set_major_formatter(yax.get_major_formatter())
        yax2.set_minor_formatter(yax.get_minor_formatter())
    elif percent:
        ts = ax2.get_yticks()
        ax2.set_yticklabels(['{0:.0%}'.format(t/percent) for t in ts])
    else:
        ts = ax2.get_yticklabels()
        [t.set_ha('right') for t in ts]
        if not pad:
            ax.figure.canvas.draw()
            rend = ax.figure.canvas.get_renderer()
            bboxes = yax.get_ticklabel_extents(rend)
            w = max(b.width for b in bboxes)
            # Value (2.8) tested with Mac Retina Display.
            # Might not work on other systems.
            if plt.get_backend().startswith('Mac'):
                pad = w/2.8 - 2
            else:
                pad = w/1.4 - 2
        yax2.set_tick_params(pad=pad)
    #fixes axis overlap in 'ggplot' style
    ax2.spines['right'].set_alpha(0)
    if month:
        ax2.tick_params(axis='y', which='minor', color=(0,0,0,0))
    else:
        ax.tick_params(axis='y', color=(0,0,0,0))
        ax2.tick_params(axis='y', color=(0,0,0,0))

    return ax2, pad

def Baseline(range):
    """Add baseline to current plot.

    Paramters
    ---------
    range : list
{'fraction_non_alphanumeric': 0.11109684048291806, 'fraction_numerical': 0.016696634985872077, 'mean_word_length': 2.4153508771929824, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '284332', 'n_tokens_mistral': 2645, 'n_tokens_neox': 2528, 'n_words': 729}