Python matplotlib.dates 模块,YearLocator() 实例源码

我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用matplotlib.dates.YearLocator()

项目:WaveletQuotes    作者:JobyKK    | 项目源码 | 文件源码
def showResult(date, scales, power, time_scale, window, file_name):
    # y_ticks = np.arange(0, 15, 2)
    import matplotlib.ticker as mticker
    import matplotlib.dates as mdates
    fig, ax = plt.subplots()
    ax.xaxis.set_major_locator(YearLocator(time_scale))
    # ax.set_yticks(y_ticks)
    ax.xaxis.set_major_locator(mticker.MaxNLocator(5))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

    ax.contourf(date, scales, power, 100)
    # ax.set_yscale('log')
    print("Wavelet saved to", file_name)
    fig.savefig(file_name)
    # fig.show()
    # fig.waitforbuttonpress()
项目:skoleni-python-knihovny    作者:tomasbedrich    | 项目源码 | 文件源码
def vykresli_spojnice(hodnoty, nadpis, jednotky):
    fig, ax = pyplot.subplots()

    pyplot.title(nadpis)
    pyplot.xlabel('datum')
    pyplot.ylabel(jednotky)

    x_hodnoty = [polozka[0] for polozka in hodnoty]
    y_hodnoty = [polozka[1] for polozka in hodnoty]

    pyplot.plot_date(x_hodnoty, y_hodnoty, 'b-', linewidth=0.5)
    pyplot.axhline(0, linewidth=0.2)

    # v jakých intervalech a jak mají vypadat popisky na ose X
    ax.xaxis.set_major_locator(YearLocator())

    pyplot.show()
项目:mizani    作者:has2k1    | 项目源码 | 文件源码
def _extend_breaks(self, major):
        """
        Append 2 extra breaks at either end of major

        If breaks of transform space are non-equidistant,
        :func:`minor_breaks` add minor breaks beyond the first
        and last major breaks. The solutions is to extend those
        breaks (in transformed space) before the minor break call
        is made. How the breaks depends on the type of transform.
        """
        trans = self.trans
        trans = trans if isinstance(trans, type) else trans.__class__
        # so far we are only certain about this extending stuff
        # making sense for log transform
        is_log = trans.__name__.startswith('log')
        diff = np.diff(major)
        step = diff[0]
        if is_log and all(diff == step):
            major = np.hstack([major[0]-step, major, major[-1]+step])
        return major


# Matplotlib's YearLocator uses different named
# arguments than the others
项目:augur    作者:nextstrain    | 项目源码 | 文件源码
def make_date_ticks(ax, fs=12):
    from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
    years    = YearLocator()
    months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
    yearsFmt = DateFormatter('%Y')
    monthsFmt = DateFormatter("%b")
    ax.tick_params(axis='x', which='major', labelsize=fs, pad=20)
    ax.tick_params(axis='x', which='minor', pad=7)
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)
    ax.xaxis.set_minor_formatter(monthsFmt)
项目:sentisignal    作者:jonathanmanfield    | 项目源码 | 文件源码
def plot_daily_inf_res(df, symbols=[], plot_top=0):
    df = df.copy()
    # data_nasdaq_top_100_preprocessed_merge.groupby('SYMBOL')
    years = mdates.YearLocator()   # every year
    months = mdates.MonthLocator()  # every month
    years_fmt = mdates.DateFormatter('%Y')

    df['max_pmi_is'] = df[[col for col in df.columns if 'pmi_is' in col]].max(axis=1)

    if len(symbols) > 0:
        df = df.loc[symbols]

    if plot_top > 0:
        idx = df.groupby('SYMBOL')['max_pmi_is'].max().sort_values(ascending=False).index[:plot_top].values
        print idx
        df = df.loc[list(idx)]
#         df = df.reindex(index=idx)

    fig, ax = plt.subplots(figsize=(15,5))
    for key, grp in df.groupby('SYMBOL'):
        print "key", key
    #     grp.reset_index()
    #     print grp.DATE

        ax.plot(grp.DATE.reset_index(drop=True), grp['max_pmi_is'], label=key)
    #     grp['D'] = pd.rolling_mean(grp['B'], window=5)    
    #     plt.plot(grp['D'], label='rolling ({k})'.format(k=key))

    # datemin = (df.DATE.min().year)
    # datemax = (df.DATE.max().year + 1)
    # print datemin, datemax
    # ax.set_xlim(datemin, datemax)
    ax.set_ylim(0, 500)


    plt.legend(loc='best')
    plt.ylabel('PMI IS (-2)')
    fig.autofmt_xdate()
    plt.show()
项目:matplotlib    作者:DaveL17    | 项目源码 | 文件源码
def setAxisScaleX(self, x_axis_bins):
        """The setAxisScaleX() method sets the bins for the X axis. Presently,
        we assume a date-based axis."""
        if self.verboseLogging:
            self.logger.threaddebug(u"Constructing the bins for the X axis.")

        if x_axis_bins == 'quarter-hourly':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 96)))
        if x_axis_bins == 'half-hourly':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 48)))
        elif x_axis_bins == 'hourly':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 24)))
        elif x_axis_bins == 'hourly_4':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 8)))
        elif x_axis_bins == 'hourly_8':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 4)))
        elif x_axis_bins == 'hourly_12':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 2)))
        elif x_axis_bins == 'daily':
            plt.gca().xaxis.set_major_locator(mdate.DayLocator(interval=1))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 6)))
        elif x_axis_bins == 'weekly':
            plt.gca().xaxis.set_major_locator(mdate.DayLocator(interval=7))
            plt.gca().xaxis.set_minor_locator(mdate.DayLocator(interval=1))
        elif x_axis_bins == 'monthly':
            plt.gca().xaxis.set_major_locator(mdate.MonthLocator(interval=1))
            plt.gca().xaxis.set_minor_locator(mdate.DayLocator(interval=1))
        elif x_axis_bins == 'yearly':
            plt.gca().xaxis.set_major_locator(mdate.YearLocator())
            plt.gca().xaxis.set_minor_locator(mdate.MonthLocator(interval=12))
项目:QTS_Research    作者:geome-mitbbs    | 项目源码 | 文件源码
def back_test_plot(self):
        import matplotlib.pyplot as plt
        import matplotlib.dates as mdates
        fig = plt.figure()
        all_lines = []
        ax = fig.add_subplot(111)
        ax.set_ylabel('PnL')
        has_right_ax = False
        if 'quant_index' in self.used_vars or \
            'quant_index1' in self.used_vars or \
            'quant_index2' in self.used_vars or \
            'quant_index3' in self.used_vars:
            has_right_ax = True
        dates = [ x[0] for x in self.pnls['portfolio'] ]
        for v in self.used_vars:
            if 'portfolio' in v:
                all_lines += ax.plot(dates, [x[1] for x in self.pnls[v]],label=v,linewidth=1)

        if has_right_ax:
            right_ax = ax.twinx()
            for v in self.used_vars:
                if 'index' in v:
                    all_lines += right_ax.plot(dates, self.quant_indices[v],label=v,linewidth=1,ls='dotted')

            right_ax.set_ylabel('quant_index')

        # format the ticks
        years = mdates.YearLocator()   # every year
        months = mdates.MonthLocator()  # every month
        yearsFmt = mdates.DateFormatter('%Y')

        ax.xaxis.set_major_locator(years)
        ax.xaxis.set_major_formatter(yearsFmt)
        ax.xaxis.set_minor_locator(months)
        datemin = min(dates)
        datemax = max(dates)
        ax.set_xlim(datemin, datemax)
        ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
        ax.grid(True)


        # rotates and right aligns the x labels, and moves the bottom of the
        # axes up to make room for them
        fig.autofmt_xdate()
        fig.tight_layout()
        plt.legend(all_lines,[l.get_label() for l in all_lines],loc='best')
        plt.show()
项目:SFBIStats    作者:royludo    | 项目源码 | 文件源码
def proportion_stackplot(df, output=None, xlabel='', ylabel='', title=''):
    """
    Pandas has a bug with it's plot(kind='area'). When moving the legend, the colors disappear.
    By default with pandas the legend sits on the graph, which is not a desired behavior.
    So this function imitates panda's formatting of an area plot, with a working well-placed legend.

    Parameters
    ----------
    df : pandas.Dataframe
        x must be a date series.
        y is any number of columns containing percentages that must add up to 100 for each row.
    output : string
        the complete output file name
    xlabel : string
    ylabel : string
    title : string

    Returns
    -------

    """

    column_names = df.columns.values
    x = df.index.date
    column_series_list = []
    for cname in column_names:
        column_series_list.append(pd.Series(df[cname]).tolist())
    fig, ax = plt.subplots()
    polys = ax.stackplot(x, column_series_list, alpha=0.8)
    ax.set_ylim([0, 100])
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    legends = []
    for poly in polys:
        legends.append(plt.Rectangle((0, 0), 1, 1, facecolor=poly.get_facecolor()[0]))
    # don't try to understand the legend displacement thing here. Believe me. Don't.
    plt.figlegend(legends, column_names, loc=7, bbox_to_anchor=(1.2 + legend_displace_factor(column_names), 0.5))
    plt.title(title, y=1.08)
    date_fmt_year = mDates.DateFormatter('%b\n%Y')
    date_fmt_month = mDates.DateFormatter('%b')
    ax.xaxis.set_major_locator(mDates.YearLocator())
    ax.xaxis.set_major_formatter(date_fmt_year)
    ax.xaxis.set_minor_locator(mDates.MonthLocator(bymonth=7))
    ax.xaxis.set_minor_formatter(date_fmt_month)
    plt.savefig(output, bbox_inches='tight')
    plt.close()