当前位置: 首页>>代码示例>>Python>>正文


Python dates.MonthLocator方法代码示例

本文整理汇总了Python中matplotlib.dates.MonthLocator方法的典型用法代码示例。如果您正苦于以下问题:Python dates.MonthLocator方法的具体用法?Python dates.MonthLocator怎么用?Python dates.MonthLocator使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.dates的用法示例。


在下文中一共展示了dates.MonthLocator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_inline_query_performance_statistics

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def get_inline_query_performance_statistics(session):
    """Plot statistics regarding performance of inline query requests."""
    creation_date = func.cast(InlineQueryRequest.created_at, Date).label(
        "creation_date"
    )
    # Group the started users by date
    strict_search_subquery = (
        session.query(
            creation_date, func.avg(InlineQueryRequest.duration).label("count")
        )
        .group_by(creation_date)
        .order_by(creation_date)
        .all()
    )
    strict_queries = [("strict", q[0], q[1]) for q in strict_search_subquery]

    # Combine the results in a single dataframe and name the columns
    request_statistics = strict_queries
    dataframe = pandas.DataFrame(
        request_statistics, columns=["type", "date", "duration"]
    )

    months = mdates.MonthLocator()  # every month
    months_fmt = mdates.DateFormatter("%Y-%m")

    # Plot each result set
    fig, ax = plt.subplots(figsize=(30, 15), dpi=120)
    for key, group in dataframe.groupby(["type"]):
        ax = group.plot(ax=ax, kind="bar", x="date", y="duration", label=key)
        ax.xaxis.set_major_locator(months)
        ax.xaxis.set_major_formatter(months_fmt)

    image = image_from_figure(fig)
    image.name = "request_duration_statistics.png"
    return image 
开发者ID:Nukesor,项目名称:sticker-finder,代码行数:37,代码来源:plot.py

示例2: apply_date_formatting_to_axis

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def apply_date_formatting_to_axis(ax):
        """ Format x-axis of input plot to a readable date format """
        ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(0), interval=1))
        ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
        ax.xaxis.grid(True, which="minor")
        ax.yaxis.grid()
        ax.xaxis.set_major_locator(dates.MonthLocator())
        ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
        return ax 
开发者ID:thomhopmans,项目名称:themarketingtechnologist,代码行数:11,代码来源:run.py

示例3: plot_results

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def plot_results(features, dates, water, clouds, save_directory=None, ground_truth_file=None):
    fig, ax = plt.subplots()
    water_line = ax.plot(dates, water, linestyle='-', color='b', linewidth=1,
                         label='Landsat Surface Area')
    ax.plot(dates, water, 'gs', ms=3)
    # ax.bar(dates, water, color='b', width=15, linewidth=0)
    # ax.bar(dates, clouds, bottom=water, color='r', width=15, linewidth=0)
    ax.xaxis.set_major_locator(mdates.YearLocator(2))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(mdates.MonthLocator([1, 4, 7, 10]))
    ax.set_xlabel('Time')
    ax.format_xdata = mdates.DateFormatter('%m/%d/%Y')
    ax.set_xlim([datetime.date(1984, 1, 1), datetime.date(1984, 12, 31)])
    ax.set_ylim([150, 190])

    lns = water_line
    if ground_truth_file is not None:
        (ground_truth_dates, ground_truth_levels) = load_ground_truth(ground_truth_file)
        ax2 = ax.twinx()
        ground_truth_line = ax2.plot(ground_truth_dates, ground_truth_levels, linestyle='--', color='r', linewidth=2, label='Measured Elevation')
        ax2.set_ylabel('Lake Elevation (ft)')
        ax2.format_ydata = (lambda x: '%g ft' % (x))
        ax2.set_ylim([6372.0, 6385.5])
        lns = lns + ground_truth_line
        ax2.set_xlim([datetime.date(1984, 6, 1), datetime.date(2015, 10, 1)])

    ax.format_ydata = (lambda x: '%g km^2' % (x))
    ax.set_ylabel('Lake Surface Area (km^2)')
    fig.suptitle(features['name'] + ' Surface Area from Landsat')
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc=4)

    ax.grid(True)
    fig.autofmt_xdate()

    if save_directory is not None:
        fig.savefig(os.path.join(save_directory, features['name'] + '.pdf')) 
开发者ID:nasa,项目名称:CrisisMappingToolkit,代码行数:39,代码来源:plot_water_level.py

示例4: plot_results

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def plot_results(features, dates, water, clouds, save_directory=None, ground_truth_file=None):
    fig, ax = plt.subplots()
    water_line = ax.plot(dates, water, linestyle='-', color='b', linewidth=1,
                         label='Landsat-Generated Surface Area')
    ax.plot(dates, water, 'gs', ms=3)
    # ax.bar(dates, water, color='b', width=15, linewidth=0)
    # ax.bar(dates, clouds, bottom=water, color='r', width=15, linewidth=0)
    ax.xaxis.set_major_locator(mdates.YearLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(mdates.MonthLocator())
    ax.set_xlabel('Time')
    ax.format_xdata = mdates.DateFormatter('%m/%d/%Y')

    if ground_truth_file is not None:
        (ground_truth_dates, ground_truth_levels) = load_ground_truth(ground_truth_file)
        ax2 = ax.twinx()
        ground_truth_line = ax2.plot(ground_truth_dates, ground_truth_levels, linestyle='--', color='r', linewidth=2, label='Measured Elevation')
        ax2.set_ylabel('Lake Elevation (ft)')
        ax2.format_ydata = (lambda x: '%g ft' % (x))
        ax2.set_ylim([6372, 6385.5])

    def onpick(event):
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        print 'onpick points:', zip(xdata[ind], ydata[ind])
    fig.canvas.mpl_connect('pick_event', onpick)

    ax.format_ydata = (lambda x: '%g km^2' % (x))
    ax.set_ylabel('Lake Surface Area (km^2)')
    fig.suptitle(features['name'] + ' Surface Area from Landsat')
    lns = water_line# + ground_truth_line
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc=4)

    ax.grid(True)
    fig.autofmt_xdate()

    if save_directory is not None:
        fig.savefig(os.path.join(save_directory, features['name'] + '.pdf')) 
开发者ID:nasa,项目名称:CrisisMappingToolkit,代码行数:43,代码来源:plot_water_levelui.py

示例5: plotYearly

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def plotYearly(dictframe, ax, uncertainty, color='#0072B2'):

    if ax is None:
        figY = plt.figure(facecolor='w', figsize=(10, 6))
        ax = figY.add_subplot(111)
    else:
        figY = ax.get_figure()
    ##
    # Find the max index for an entry of each month
    ##
    months = dictframe.ds.dt.month
    ind = []
    for month in range(1,13):
        ind.append(max(months[months == month].index.tolist()))
    ##
    # Plot from the minimum of those maximums on (this will almost certainly result in only 1 year plotted)
    ##
    ax.plot(dictframe['ds'][min(ind):], dictframe['yearly'][min(ind):], ls='-', c=color)
    if uncertainty:
        ax.fill_between(dictframe['ds'].values[min(ind):], dictframe['yearly_lower'][min(ind):], dictframe['yearly_upper'][min(ind):], color=color, alpha=0.2)
    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
    months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
    ax.xaxis.set_major_formatter(FuncFormatter(
        lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
    ax.xaxis.set_major_locator(months)
    ax.set_xlabel('Day of year')
    ax.set_ylabel('yearly')
    figY.tight_layout()
    return figY 
开发者ID:CollinRooney12,项目名称:htsprophet,代码行数:31,代码来源:htsPlot.py

示例6: get_vote_activity

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def get_vote_activity(session):
    """Create a plot showing the inline usage statistics."""
    creation_date = func.date_trunc("day", Vote.created_at).label("creation_date")
    votes = (
        session.query(creation_date, func.count(Vote.id).label("count"))
        .group_by(creation_date)
        .order_by(creation_date)
        .all()
    )
    total_votes = [("Total votes", q[0], q[1]) for q in votes]

    # Grid style
    plt.style.use("seaborn-whitegrid")

    # Combine the results in a single dataframe and name the columns
    dataframe = pandas.DataFrame(total_votes, columns=["type", "date", "votes"])

    months = mdates.MonthLocator()  # every month
    months_fmt = mdates.DateFormatter("%Y-%m")

    max_number = max([vote[2] for vote in total_votes])
    # Plot each result set
    fig, ax = plt.subplots(figsize=(30, 15), dpi=120)
    for key, group in dataframe.groupby(["type"]):
        ax = group.plot(ax=ax, kind="bar", x="date", y="votes", label=key)
        ax.xaxis.set_major_locator(months)
        ax.xaxis.set_major_formatter(months_fmt)
        ax.yaxis.set_ticks(np.arange(0, max_number, 100))

    image = image_from_figure(fig)
    image.name = "vote_statistics.png"
    return image 
开发者ID:Nukesor,项目名称:ultimate-poll-bot,代码行数:34,代码来源:plot.py

示例7: PlotScalerDateAdjust

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def PlotScalerDateAdjust(minDate:datetime, maxDate:datetime, ax):
	if type(minDate)==str:
		daysInGraph = DateDiffDays(minDate,maxDate)
	else:
		daysInGraph = (maxDate-minDate).days
	if daysInGraph >= 365*3:
		majorlocator =  mdates.YearLocator()
		minorLocator = mdates.MonthLocator()
		majorFormatter = mdates.DateFormatter('%m/%d/%Y')
	elif daysInGraph >= 365:
		majorlocator =  mdates.MonthLocator()
		minorLocator = mdates.WeekdayLocator()
		majorFormatter = mdates.DateFormatter('%m/%d/%Y')
	elif daysInGraph < 90:
		majorlocator =  mdates.DayLocator()
		minorLocator = mdates.DayLocator()
		majorFormatter =  mdates.DateFormatter('%m/%d/%Y')
	else:
		majorlocator =  mdates.WeekdayLocator()
		minorLocator = mdates.DayLocator()
		majorFormatter =  mdates.DateFormatter('%m/%d/%Y')
	ax.xaxis.set_major_locator(majorlocator)
	ax.xaxis.set_major_formatter(majorFormatter)
	ax.xaxis.set_minor_locator(minorLocator)
	#ax.xaxis.set_minor_formatter(daysFmt)
	ax.set_xlim(minDate, maxDate) 
开发者ID:TimRivoli,项目名称:Stock-Price-Trade-Analyzer,代码行数:28,代码来源:PriceTradeAnalyzer.py

示例8: main

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def main(args):
    _, fetch = load_dataset(SP500, shuffle=False)
    dates, returns = fetch()
    init_rng_key, sample_rng_key = random.split(random.PRNGKey(args.rng_seed))
    model_info = initialize_model(init_rng_key, model, model_args=(returns,))
    init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')
    hmc_state = init_kernel(model_info.param_info, args.num_warmup, rng_key=sample_rng_key)
    hmc_states = fori_collect(args.num_warmup, args.num_warmup + args.num_samples, sample_kernel, hmc_state,
                              transform=lambda hmc_state: model_info.postprocess_fn(hmc_state.z),
                              progbar=False if "NUMPYRO_SPHINXBUILD" in os.environ else True)
    print_results(hmc_states, dates)

    fig, ax = plt.subplots(1, 1)
    dates = mdates.num2date(mdates.datestr2num(dates))
    ax.plot(dates, returns, lw=0.5)
    # format the ticks
    ax.xaxis.set_major_locator(mdates.YearLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(mdates.MonthLocator())

    ax.plot(dates, jnp.exp(hmc_states['s'].T), 'r', alpha=0.01)
    legend = ax.legend(['returns', 'volatility'], loc='upper right')
    legend.legendHandles[1].set_alpha(0.6)
    ax.set(xlabel='time', ylabel='returns', title='Volatility of S&P500 over time')

    plt.savefig("stochastic_volatility_plot.pdf")
    plt.tight_layout() 
开发者ID:pyro-ppl,项目名称:numpyro,代码行数:29,代码来源:stochastic_volatility.py

示例9: getDatasForOneRouteForOneDepartureDate

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def getDatasForOneRouteForOneDepartureDate(route, departureDate):
    X = getOneRouteData(datas, route)
    minDeparture = np.amin(X[:,8])
    maxDeparture = np.amax(X[:,8])
    print minDeparture
    print maxDeparture

    # get specific departure date datas
    X = X[np.where(X[:, 8]==departureDate)[0], :]

    # get the x values
    xaxis = X[:,9] # observed date state
    print xaxis
    xaxis = departureDate-1-xaxis
    print xaxis

    tmp = xaxis
    startdate = "20151109"
    xaxis = [pd.to_datetime(startdate) + pd.DateOffset(days=state) for state in tmp]
    print xaxis

    # get the y values
    yaxis = X[:,12]


    # every monday
    mondays = WeekdayLocator(MONDAY)

    # every 3rd month
    months = MonthLocator(range(1, 13), bymonthday=1, interval=01)
    days = WeekdayLocator(byweekday=1, interval=2)
    monthsFmt = DateFormatter("%b. %d, %Y")

    fig, ax = plt.subplots()
    ax.plot_date(xaxis, yaxis, 'r--')
    ax.plot_date(xaxis, yaxis, 'bo')
    ax.xaxis.set_major_locator(days)
    ax.xaxis.set_major_formatter(monthsFmt)
    #ax.xaxis.set_minor_locator(mondays)
    ax.autoscale_view()
    #ax.xaxis.grid(False, 'major')
    #ax.xaxis.grid(True, 'minor')
    ax.grid(True)
    plt.xlabel('Date')
    plt.ylabel('Price in Euro')

    fig.autofmt_xdate()
    plt.show()

    """
    # plot
    line1, = plt.plot(xaxis, yaxis, 'r--')
    line2, = plt.plot(xaxis, yaxis, 'bo')
    #plt.legend([line2], ["Price"])
    plt.xlabel('States')
    plt.ylabel('Price in Euro')
    plt.show()
    """ 
开发者ID:junlulocky,项目名称:AirTicketPredicting,代码行数:60,代码来源:priceBehaviorAnalysis.py

示例10: set_x_axis_locator

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def set_x_axis_locator(self, x_from, x_to):
        x_axis_range = x_to - x_from
        years = mdates.YearLocator()
        if x_axis_range < 200:
            self.ax.xaxis.set_major_locator(mdates.MonthLocator())
            self.ax.xaxis.set_major_formatter(mdates.DateFormatter('%b-%Y'))
            # self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        elif x_axis_range < 7*365:
            self.ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
            self.ax.xaxis.set_major_locator(years)
            self.ax.xaxis.set_minor_locator(mdates.MonthLocator())
        else:
            self.ax.xaxis.set_major_locator(years)
            self.ax.xaxis.set_major_locator(mdates.AutoDateLocator()) 
开发者ID:itaidagan,项目名称:FranchiseRevenueComparison,代码行数:16,代码来源:FranchiseAnimation.py

示例11: set_x_axis_locator

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def set_x_axis_locator(ax, x_from, x_to):
    x_axis_range = x_to - x_from
    if x_axis_range < 300:
        ax.xaxis.set_major_locator(mdates.MonthLocator())
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%b-%Y'))
    elif x_axis_range < 4*365:
        ax.xaxis.set_major_locator(years)
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    else:
        ax.xaxis.set_major_locator(mdates.AutoDateLocator())
    return ax 
开发者ID:itaidagan,项目名称:FranchiseRevenueComparison,代码行数:13,代码来源:animation_funcs.py

示例12: back_test_plot

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
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() 
开发者ID:geome-mitbbs,项目名称:QTS_Research,代码行数:49,代码来源:Trade_Algo.py

示例13: activity

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def activity(members):
    """Visualize member activity over whole chat period.

    Display weekly means for every user in a spaghetti plot emphasizing
    one user at a time.
    """
    # compute weekly means
    fig, axarr = plt.subplots(len(members), sharex=True, sharey=True, squeeze=False)
    axarr = [ax for lt in axarr for ax in lt]
    index = (7 - Member.first.weekday()) % 7
    weeks = [
        [mean(members[i].days[k:k+7]) for k in range(index, Member.period-6, 7)]
        for i in range(len(members))
    ]
    dates = [Member.first.date() + dt.timedelta(days=i) for i in range(index, Member.period-6, 7)]

    # plot multiple times with different emphasis
    for i, member in enumerate(members):
        for j in range(len(members)):
            axarr[i].plot(dates, weeks[j], color=COLORS[3], linewidth=0.5)
        axarr[i].plot(dates, weeks[i], color=COLORS[i+4])
        # set style attributes
        axarr[i].yaxis.grid(True)
        if weeks[0]: axarr[i].set_ylim(0, 1.1*max([max(l) for l in weeks]))
        axarr[i].set_ylabel(member.name, labelpad=20, rotation=0, ha='right')
        plt.xlim(
            Member.first.date() - dt.timedelta(days=1),
            Member.first.date() + dt.timedelta(Member.period)
        )
        # set formatter and locator (autolocator has problems setting good date xticks)
        axarr[i].xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
        axarr[i].xaxis.set_major_locator(mdates.MonthLocator(interval=(Member.period // 250) or 1))
        axarr[i].callbacks.connect(
            'xlim_changed',
            lambda ax: ax.xaxis.set_major_locator(
                mdates.MonthLocator(interval=(int(ax.get_xlim()[1] - ax.get_xlim()[0]) // 250) or 1)
            )
        )

    # set title
    fig.add_subplot(111, frameon=False)
    plt.tick_params(labelcolor='none', left=False, bottom=False)
    plt.title('User Activity (Messages / Day Weekly Means)') 
开发者ID:empicano,项目名称:whatsapp-analyzer,代码行数:45,代码来源:analyzer.py

示例14: tsindex

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def tsindex(ax):
    """
        Reset the axis parameters to look nice!
    """
    # Get dt in days
    dt = ax.get_xlim()[-1] - ax.get_xlim()[0]

    if dt <= 1./24.:   # less than one hour
        pass
    elif dt <= 1.:     # less than one day
        ax.xaxis.set_minor_locator( dates.HourLocator() )
        ax.xaxis.set_minor_formatter( dates.DateFormatter(""))

        ax.xaxis.set_major_locator( dates.HourLocator( interval=3))
        ax.xaxis.set_major_formatter( dates.DateFormatter("%-I %p"))
    elif dt <= 7.:      # less than one week
        ax.xaxis.set_minor_locator( dates.DayLocator())
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.DayLocator( bymonthday=[1, 8, 15, 22]) )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    elif dt <= 14.:     # less than two weeks
        ax.xaxis.set_minor_locator( dates.DayLocator())
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.DayLocator( bymonthday=[1, 15]) )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    elif dt <= 28.:     # less than four weeks
        ax.xaxis.set_minor_locator( dates.DayLocator())
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.MonthLocator() )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    elif dt <= 4 * 30.: # less than four months
        ax.xaxis.set_minor_locator( dates.DayLocator( bymonthday=[1, 7, 14, 21] ))
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.MonthLocator())
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    else:
        ax.xaxis.set_minor_locator( dates.MonthLocator(interval=2) )
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%b"))

        ax.xaxis.set_major_locator( dates.MonthLocator(bymonth=[1]) )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%Y"))


    return ax 
开发者ID:dhhagan,项目名称:py-openaq,代码行数:50,代码来源:viz.py

示例15: createLinePlot

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import MonthLocator [as 别名]
def createLinePlot(self):
        nseries = len(self.meta())
        res = self.results()
        meta = self.meta()

        timeSeries = [datetime.fromtimestamp(m[0]["time"] / 1000) for m in res]

        means = [[np.nan] * len(res) for n in range(0, nseries)]

        plotSeries = self.computeOptions().get_plot_series() if self.computeOptions is not None else None
        if plotSeries is None:
            plotSeries = "mean"

        for n in range(0, len(res)):
            timeSlot = res[n]
            for seriesValues in timeSlot:
                means[seriesValues['ds']][n] = seriesValues[plotSeries]

        x = timeSeries

        fig, axMain = plt.subplots()
        fig.set_size_inches(11.0, 8.5)
        fig.autofmt_xdate()

        title = ', '.join(set([m['title'] for m in meta]))
        sources = ', '.join(set([m['source'] for m in meta]))
        dateRange = "%s - %s" % (timeSeries[0].strftime('%b %Y'), timeSeries[-1].strftime('%b %Y'))

        axMain.set_title("%s\n%s\n%s" % (title, sources, dateRange))
        axMain.set_xlabel('Date')
        axMain.grid(True)
        axMain.xaxis.set_major_locator(mdates.YearLocator())
        axMain.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
        axMain.xaxis.set_minor_locator(mdates.MonthLocator())
        axMain.format_xdata = mdates.DateFormatter('%Y-%m-%d')

        plots = []

        for n in range(0, nseries):
            if n == 0:
                ax = axMain
            else:
                ax = ax.twinx()

            plots += ax.plot(x, means[n], color=self.__SERIES_COLORS[n], zorder=10, linewidth=3,
                             label=meta[n]['title'])
            ax.set_ylabel(meta[n]['units'])

        labs = [l.get_label() for l in plots]
        axMain.legend(plots, labs, loc=0)

        sio = StringIO()
        plt.savefig(sio, format='png')
        return sio.getvalue() 
开发者ID:apache,项目名称:incubator-sdap-nexus,代码行数:56,代码来源:TimeSeriesSpark.py


注:本文中的matplotlib.dates.MonthLocator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。