Exemplo n.º 1
0
def _generate_activity_count_plot(activity_data: pd.DataFrame,
                                  ax: mpl.axes.Axes, colours: str):
    """
    Generate a bar plot of activity counts over time (by type).

    Arguments:
    activity data - A pandas DataFrame containing the activity data.
    ax - A set of matplotlib axes to generate the plot on.
    colours - A name of the colour palette to generate the plot with.
    """

    # Group the activity data by month and calculate the count of each activity type
    data = (activity_data.groupby([activity_data.index.to_period('M'), 'type'
                                   ]).size().to_frame('count').reset_index())

    # Generate and format the bar plot
    sns.barplot(x='start_date_local',
                y='count',
                hue='type',
                data=data,
                palette=colours,
                ax=ax)
    ax.set(title='Activities over time',
           ylabel='Number of activities',
           xlabel='Month')
    ax.set_xticklabels(ax.get_xticklabels(),
                       rotation=45,
                       horizontalalignment='right')
    ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.grid(b=True, which='major', linewidth=1.0)
    ax.yaxis.grid(b=True, which='minor', linewidth=0.5)
    ax.set_axisbelow(True)
Exemplo n.º 2
0
def _generate_commute_count_plot(commute_data: pd.DataFrame, ax: mpl.axes.Axes,
                                 colours: dict):
    """
    Generate a bar plot of number of commutes per month.

    Arguments:
    commute_data - A pandas DataFrame containing the commute activity data.
    ax - A set of matplotlib axes to generate the plot on.
    colours - A dictionary of colours to generate the plot with.
    """

    # Group the commute data by month
    data = commute_data.resample('M').count()

    # Generate and format the bar plot
    sns.barplot(x=data.index.to_period('M'),
                y=data['distance'],
                color=colours['commute_count'],
                ax=ax)
    ax.set(ylabel='Number of commutes', xlabel='Month')
    ax.set_xticklabels(ax.get_xticklabels(),
                       rotation=45,
                       horizontalalignment='right')
    ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.grid(b=True, which='major', linewidth=1.0)
    ax.yaxis.grid(b=True, which='minor', linewidth=0.5)
    ax.set_axisbelow(True)
Exemplo n.º 3
0
def _generate_mean_distance_plot(activity_data: pd.DataFrame,
                                 ax: mpl.axes.Axes, colour_palette: list):
    """
    Generate a bar plot of mean activity distance over time (by type).

    Arguments:
    activity data - A pandas DataFrame containing the activity data.
    ax - A set of matplotlib axes to generate the plot on.
    colour_palette - The colour palette to generate the plot with.
    """

    # Group the activity data by month and calculate the mean distance of each activity type
    data = activity_data.groupby([activity_data.index.to_period('Y'),
                                  'type']).mean().reset_index()

    # Generate and format the bar plot
    sns.barplot(x='start_date_local',
                y='distance',
                hue='type',
                data=data,
                palette=colour_palette,
                ax=ax)
    ax.set(title='Mean activity distance over time',
           ylabel='Mean distance (km)',
           xlabel='Year')
    ax.set_xticklabels(ax.get_xticklabels(),
                       rotation=45,
                       horizontalalignment='right')
    ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.grid(b=True, which='major', linewidth=1.0)
    ax.yaxis.grid(b=True, which='minor', linewidth=0.5)
    ax.set_axisbelow(True)
Exemplo n.º 4
0
def _generate_commute_days_plot(commute_data: pd.DataFrame, ax: mpl.axes.Axes,
                                colours: dict):
    """
    Generate a line plot of commute days per year.

    Arguments:
    commute_data - A pandas DataFrame containing the commute activity data.
    ax - A set of matplotlib axes to generate the plot on.
    colours - A dictionary of colours to generate the plot with.
    """

    # Group the commute data by day
    data = commute_data.groupby(commute_data.index.to_period('D')).agg(
        {'distance': 'mean'})

    # Generate and format the line plot
    sns.lineplot(x=data.index.year.value_counts().index,
                 y=data.index.year.value_counts(),
                 color=colours['commute_days'],
                 marker='o',
                 ax=ax)
    ax.set(ylabel='Commute days', xlabel='Year')
    ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.grid(b=True, which='major', linewidth=1.0)
    ax.yaxis.grid(b=True, which='minor', linewidth=0.5)
Exemplo n.º 5
0
def text_box(ax: mp.axes.Axes,
             text: str,
             colors: List[str] = ["#FFFFFF", "#000000"],
             fontsize: int = 14,
             x: int = 0,
             y: int = 0) -> bool:
    log = logging.getLogger('text_box')
    log.info(" >>")
    rv = False
    try:
        edgecolor = "none"
        boxstyle = "square"
        if len(colors) >= 3 and colors[2] is not None:
            edgecolor = colors[2]
            boxstyle = "round,pad=1"
        ax.text(x,
                y,
                text,
                ha="left",
                va="center",
                bbox=dict(boxstyle=boxstyle,
                          facecolor=colors[0],
                          edgecolor=edgecolor),
                color=colors[1],
                fontsize=fontsize)
        set_axes_common_properties(ax, no_grid=True)
        ax.get_xaxis().set_ticks([])
        ax.get_yaxis().set_ticks([])

    except Exception as ex:
        print("text_box failed - {ex}".format(ex=ex))
    else:
        rv = True
    log.info(" <<")
    return rv
Exemplo n.º 6
0
def pretty_axes(ax: matplotlib.axes.Axes) -> matplotlib.axes.Axes:
    """Better looking matplotlib axes object."""
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().set_visible(False)
    ax.grid(axis="y", alpha=0.75)
    return ax
Exemplo n.º 7
0
def __configPlot2(df: pd.DataFrame, ax: matplotlib.axes.Axes):
    """グラフの描画設定を行う。
    """
    ax.get_xaxis().set_major_locator(ticker.MaxNLocator(integer=True))
    ax.get_yaxis().set_major_locator(ticker.MaxNLocator(integer=True))
    ax.ticklabel_format(style='plain',
                        axis='both',
                        useOffset=False,
                        useMathText=False)
    ax.margins(x=0, y=0)
    ax.set_xticks(list(df.index))
    ax.set_xticklabels(list(df['Gregorian']), rotation=30)
Exemplo n.º 8
0
def _generate_commute_distance_plot(commute_data: pd.DataFrame,
                                    ax: mpl.axes.Axes, colours: dict):
    """
    Generate a line plot of total and mean commute distance per year.

    Arguments:
    commute_data - A pandas DataFrame containing the commute activity data.
    ax - A set of matplotlib axes to generate the plot on.
    colours - A dictionary of colours to generate the plot with.
    """

    # Group the commute data by year
    data = commute_data.resample('Y').agg({'distance': ['sum', 'mean']})

    # Generate and format the total distance line plot
    sns.lineplot(x=data.index.year,
                 y=data['distance', 'sum'],
                 color=colours['commute_distance_sum'],
                 marker='o',
                 ax=ax)
    ax.set_xlabel('Year')
    ax.set_ylabel('Total commute distance (km)',
                  color=colours['commute_distance_sum'])
    ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.grid(b=True, which='major', linewidth=1.0)
    ax.yaxis.grid(b=True, which='minor', linewidth=0.5)

    # Generate and format the mean distance line plot
    ax_mean = ax.twinx()
    sns.lineplot(x=data.index.year,
                 y=data['distance', 'mean'],
                 color=colours['commute_distance_mean'],
                 marker='o',
                 ax=ax_mean)
    ax_mean.set_ylabel('Average commute distance (km)',
                       color=colours['commute_distance_mean'])
Exemplo n.º 9
0
 def axis(self, axs: mpl.axes.Axes) -> None:
     """Modify font of axis-labels."""
     if not self.axisfont:
         return ()
     return (axs.get_xaxis().get_label(), axs.get_yaxis().get_label())
Exemplo n.º 10
0
def plot_vaccinations_by_time(df: pd.DataFrame,
                              df_delivered: pd.DataFrame,
                              ax: mp.axes.Axes,
                              wich: str = "first") -> ResultValue:
    log = logging.getLogger('plot_vaccinations_by_time')
    log.info(" >>")
    try:
        ln_one_color = "#f08814"
        ln_two_color = "#92b7e9"
        ln_one_label = "Cumulata numero vaccinazioni"
        ln_two_label = "Distribuzione giornaliera"

        grp_by_time = df.groupby("data_somministrazione").sum()
        x = grp_by_time.index.values
        y = grp_by_time["prima_dose"]
        y_cum_sum = grp_by_time["prima_dose"].cumsum()

        set_axes_common_properties(ax, no_grid=False)
        ax.get_yaxis().set_major_formatter(
            mp.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

        remove_tick_lines('x', ax)
        remove_tick_lines('y', ax)

        ax.set_xticks(x)
        ax.set_xticklabels(x, rotation=80)
        ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%y"))
        ax.xaxis.set_minor_formatter(mdates.DateFormatter("%d/%m"))
        ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
        ax.set_ylabel(ln_one_label, fontsize=14)
        ax.set_xlabel("Data", fontsize=14)
        ax.set_title("Vaccinazioni nel tempo - prima dose", fontsize=18)
        ax.tick_params(axis='y', colors=ln_one_color)
        ax.yaxis.label.set_color(ln_one_color)

        ax.scatter(x, y_cum_sum, color=ln_one_color, s=30, marker='.')
        ln_one = ax.plot(x,
                         y_cum_sum,
                         'b-',
                         linewidth=2,
                         color=ln_one_color,
                         label=ln_one_label)

        result = plot_delivered_vaccines_quantity(df_delivered, ax)
        if result.is_in_error() == True:
            log.error(result())
            return result
        line_three = result()

        ax_dec = ax.twinx()

        remove_tick_lines('y', ax_dec)
        remove_tick_lines('x', ax_dec)

        set_axes_common_properties(ax_dec, no_grid=True)

        ax_dec.scatter(x, y, color=ln_two_color, s=30, marker='.')
        ln_two = ax_dec.plot(x,
                             y,
                             'b-',
                             linewidth=2,
                             color=ln_two_color,
                             label=ln_two_label)

        ax_dec.set_ylabel(ln_two_label, fontsize=14)
        ax_dec.yaxis.label.set_color(ln_two_color)
        ax_dec.tick_params(axis='y', colors=ln_two_color)

        lns = ln_one + ln_two + line_three
        labs = [l.get_label() for l in lns]
        ax.legend(lns, labs, loc='upper left')

    except Exception as ex:
        log.error("Exception caught - {ex}".format(ex=ex))
        return ResultKo(ex)
    log.info(" <<")
    return ResultOk(True)