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


Python matplotlib.dates方法代码示例

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


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

示例1: find_previous_inflow_date

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def find_previous_inflow_date(df, inflow_dates):
    """
    Calculates no of days from inflow event for dates in df

    :param df: Input df
    :param inflow_dates:datetime index of inflow pandas dataframe
    :return:
    """
    # insert_dummy_columns
    df['days_from_inflow'] = 0
    for date in df.index:
        deltas = inflow_dates - date
        days_from_inflow = np.max([n for n in deltas.days if n < 0])
        df.loc[date, 'days_from_inflow'] = np.abs(days_from_inflow)
    return df

# print len(inflow_days_591_df.index) 
开发者ID:Kirubaharan,项目名称:hydrology,代码行数:19,代码来源:check_dam_talk_plot.py

示例2: extractWeekendHighlights

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def extractWeekendHighlights(dates):
    weekendsOut = []
    weekendSearch = [5, 6]
    weekendStart = None
    for i, date in enumerate(dates):
        if date.weekday() in weekendSearch:
            if weekendStart is None:
                # Mark start of weekend
                weekendStart = i
        else:
            if weekendStart is not None:
                # Mark end of weekend
                weekendsOut.append((
                    weekendStart, i, WEEKEND_HIGHLIGHT_COLOR, HIGHLIGHT_ALPHA
                ))
                weekendStart = None

    # Cap it off if we're still in the middle of a weekend
    if weekendStart is not None:
        weekendsOut.append((
            weekendStart, len(dates)-1, WEEKEND_HIGHLIGHT_COLOR, HIGHLIGHT_ALPHA
        ))

    return weekendsOut 
开发者ID:iizukak,项目名称:ecg-htm,代码行数:26,代码来源:nupic_anomaly_output.py

示例3: datestr2num

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def datestr2num(d, default=None):
    """
    Convert a date string to a datenum using
    :func:`dateutil.parser.parse`.

    Parameters
    ----------
    d : string or sequence of strings
        The dates to convert.

    default : datetime instance
        The default date to use when fields are missing in `d`.
    """
    if cbook.is_string_like(d):
        dt = dateutil.parser.parse(d, default=default)
        return date2num(dt)
    else:
        if default is not None:
            d = [dateutil.parser.parse(s, default=default) for s in d]
        d = np.asarray(d)
        if not d.size:
            return d
        return date2num(_dateutil_parser_parse_np_vectorized(d)) 
开发者ID:miloharper,项目名称:neural-network-animation,代码行数:25,代码来源:dates.py

示例4: datestr2num

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def datestr2num(d, default=None):
    """
    Convert a date string to a datenum using
    :func:`dateutil.parser.parse`.

    Parameters
    ----------
    d : string or sequence of strings
        The dates to convert.

    default : datetime instance, optional
        The default date to use when fields are missing in *d*.
    """
    if isinstance(d, str):
        dt = dateutil.parser.parse(d, default=default)
        return date2num(dt)
    else:
        if default is not None:
            d = [dateutil.parser.parse(s, default=default) for s in d]
        d = np.asarray(d)
        if not d.size:
            return d
        return date2num(_dateutil_parser_parse_np_vectorized(d)) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:25,代码来源:dates.py

示例5: tick_values

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def tick_values(self, vmin, vmax):
        delta = relativedelta(vmax, vmin)

        # We need to cap at the endpoints of valid datetime
        try:
            start = vmin - delta
        except (ValueError, OverflowError):
            start = _from_ordinalf(1.0)

        try:
            stop = vmax + delta
        except (ValueError, OverflowError):
            # The magic number!
            stop = _from_ordinalf(3652059.9999999)

        self.rule.set(dtstart=start, until=stop)

        dates = self.rule.between(vmin, vmax, True)
        if len(dates) == 0:
            return date2num([vmin, vmax])
        return self.raise_if_exceeds(date2num(dates)) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:23,代码来源:dates.py

示例6: __init__

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def __init__(self, byweekday=1, interval=1, tz=None):
        """
        Mark every weekday in *byweekday*; *byweekday* can be a number or
        sequence.

        Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
        SU, the constants from :mod:`dateutil.rrule`, which have been
        imported into the :mod:`matplotlib.dates` namespace.

        *interval* specifies the number of weeks to skip.  For example,
        ``interval=2`` plots every second week.
        """
        if isinstance(byweekday, np.ndarray):
            # This fixes a bug in dateutil <= 2.3 which prevents the use of
            # numpy arrays in (among other things) the bymonthday, byweekday
            # and bymonth parameters.
            [x.item() for x in byweekday.astype(int)]

        rule = rrulewrapper(DAILY, byweekday=byweekday,
                            interval=interval, **self.hms0d)
        RRuleLocator.__init__(self, rule, tz) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:23,代码来源:dates.py

示例7: __init__

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def __init__(self, *args, **kwargs):
    super(NuPICPlotOutput, self).__init__(*args, **kwargs)
    self.names = [self.name]
    # Turn matplotlib interactive mode on.
    plt.ion()
    self.dates = []
    self.convertedDates = []
    self.actualValues = []
    self.predictedValues = []
    self.actualLines = []
    self.predictedLines = []
    self.linesInitialized = False
    self.graphs = []
    plotCount = len(self.names)
    plotHeight = max(plotCount * 3, 6)
    fig = plt.figure(figsize=(14, plotHeight))
    gs = gridspec.GridSpec(plotCount, 1)
    for index in range(len(self.names)):
      self.graphs.append(fig.add_subplot(gs[index, 0]))
      plt.title(self.names[index])
      plt.ylabel('Frequency Bucket')
      plt.xlabel('Seconds')
    plt.tight_layout() 
开发者ID:htm-community,项目名称:nupic.critic,代码行数:25,代码来源:nupic_output.py

示例8: initializeLines

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def initializeLines(self, timestamps):
    for index in range(len(self.names)):
      print "initializing %s" % self.names[index]
      # graph = self.graphs[index]
      self.dates.append(deque([timestamps[index]] * WINDOW, maxlen=WINDOW))
      # print self.dates[index]
      # self.convertedDates.append(deque(
      #   [date2num(date) for date in self.dates[index]], maxlen=WINDOW
      # ))
      self.actualValues.append(deque([0.0] * WINDOW, maxlen=WINDOW))
      self.predictedValues.append(deque([0.0] * WINDOW, maxlen=WINDOW))

      actualPlot, = self.graphs[index].plot(
        self.dates[index], self.actualValues[index]
      )
      self.actualLines.append(actualPlot)
      predictedPlot, = self.graphs[index].plot(
        self.dates[index], self.predictedValues[index]
      )
      self.predictedLines.append(predictedPlot)
    self.linesInitialized = True 
开发者ID:htm-community,项目名称:nupic.critic,代码行数:23,代码来源:nupic_output.py

示例9: plotFI

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def plotFI(dt, fi, mintime):
    
    """
    Creates subplot for frequency index scatterplot
    
    dt: Array containing times of repeaters
    fi: Array containing frequency index values of repeaters
    mintime: Minimum time to be plotted
    
    """
    
    fig = bokehFigure(title='Frequency Index')
    fig.yaxis.axis_label = 'FI'
    fig.circle(matplotlib.dates.num2date(dt[dt>=mintime]), fi[dt>=mintime], color='red',
        line_alpha=0, size=3, fill_alpha=0.5)
    
    return fig 
开发者ID:ahotovec,项目名称:REDPy,代码行数:19,代码来源:plotting.py

示例10: PlotDataFrame

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def PlotDataFrame(df:pd.DataFrame, title:str, xlabel:str, ylabel:str, adjustScale:bool=True, fileName:str = '', dpi:int = 600):
	if df.shape[0] >= 4:
		PlotInitDefaults()
		ax=df.plot(title=title, linewidth=.75)
		ax.set_xlabel(xlabel)
		ax.set_ylabel(ylabel)
		ax.tick_params(axis='x', rotation=70)
		ax.grid(b=True, which='major', color='black', linestyle='solid', linewidth=.5)
		ax.grid(b=True, which='minor', color='0.65', linestyle='solid', linewidth=.3)
		if adjustScale:
			dates= df.index.get_level_values('Date')
			minDate = dates.min()
			maxDate = dates.max()
			PlotScalerDateAdjust(minDate, maxDate, ax)
		if not fileName =='':
			if not fileName[-4] == '.': fileName+= '.png'
			plt.savefig(fileName, dpi=dpi)			
		else:
			fig = plt.figure(1)
			fig.canvas.set_window_title(title)
			plt.show()
		plt.close('all') 
开发者ID:TimRivoli,项目名称:Stock-Price-Trade-Analyzer,代码行数:24,代码来源:PriceTradeAnalyzer.py

示例11: _render_volume

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def _render_volume(self, current_step, net_worth, dates, step_range):
        self.volume_ax.clear()

        volume = np.array(self.df['Volume'].values[step_range])

        pos = self.df['Open'].values[step_range] - \
            self.df['Close'].values[step_range] < 0
        neg = self.df['Open'].values[step_range] - \
            self.df['Close'].values[step_range] > 0

        # Color volume bars based on price direction on that date
        self.volume_ax.bar(dates[pos], volume[pos], color=UP_COLOR,
                           alpha=0.4, width=1, align='center')
        self.volume_ax.bar(dates[neg], volume[neg], color=DOWN_COLOR,
                           alpha=0.4, width=1, align='center')

        # Cap volume axis height below price chart and hide ticks
        self.volume_ax.set_ylim(0, max(volume) / VOLUME_CHART_HEIGHT)
        self.volume_ax.yaxis.set_ticks([]) 
开发者ID:notadamking,项目名称:Stock-Trading-Visualization,代码行数:21,代码来源:StockTradingGraph.py

示例12: render

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def render(self, current_step, net_worth, trades, window_size=40):
        self.net_worths[current_step] = net_worth

        window_start = max(current_step - window_size, 0)
        step_range = range(window_start, current_step + 1)

        # Format dates as timestamps, necessary for candlestick graph
        dates = np.array([date2num(x)
                          for x in self.df['Date'].values[step_range]])

        self._render_net_worth(current_step, net_worth, step_range, dates)
        self._render_price(current_step, net_worth, dates, step_range)
        self._render_volume(current_step, net_worth, dates, step_range)
        self._render_trades(current_step, trades, step_range)

        # Format the date ticks to be more easily read
        self.price_ax.set_xticklabels(self.df['Date'].values[step_range], rotation=45,
                                      horizontalalignment='right')

        # Hide duplicate net worth date labels
        plt.setp(self.net_worth_ax.get_xticklabels(), visible=False)

        # Necessary to view frames before they are unrendered
        plt.pause(0.001) 
开发者ID:notadamking,项目名称:Stock-Trading-Visualization,代码行数:26,代码来源:StockTradingGraph.py

示例13: print_results

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def print_results(posterior, dates):
    def _print_row(values, row_name=''):
        quantiles = jnp.array([0.2, 0.4, 0.5, 0.6, 0.8])
        row_name_fmt = '{:>8}'
        header_format = row_name_fmt + '{:>12}' * 5
        row_format = row_name_fmt + '{:>12.3f}' * 5
        columns = ['(p{})'.format(q * 100) for q in quantiles]
        q_values = jnp.quantile(values, quantiles, axis=0)
        print(header_format.format('', *columns))
        print(row_format.format(row_name, *q_values))
        print('\n')

    print('=' * 20, 'sigma', '=' * 20)
    _print_row(posterior['sigma'])
    print('=' * 20, 'nu', '=' * 20)
    _print_row(posterior['nu'])
    print('=' * 20, 'volatility', '=' * 20)
    for i in range(0, len(dates), 180):
        _print_row(jnp.exp(posterior['s'][:, i]), dates[i]) 
开发者ID:pyro-ppl,项目名称:numpyro,代码行数:21,代码来源:stochastic_volatility.py

示例14: save_roast_graph_csv

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def save_roast_graph_csv(self):
        try:
            file_name = QtWidgets.QFileDialog.getSaveFileName(
                QtWidgets.QWidget(),
                'Save Roast Graph CSV',
                os.path.expanduser('~/'),
                'CSV (*.csv);;All Files (*)')
            with open(file_name[0], 'w') as outfile:
                outfile.write("Seconds,Temperature\n")
                if not self.graphXValueList:
                    return
                init_time = matplotlib.dates.num2date(self.graphXValueList[0])
                for x_val,y_val in zip(self.graphXValueList,self.graphYValueList):
                    x_time = matplotlib.dates.num2date(x_val)
                    elapsed_seconds = (x_time - init_time).seconds
                    outfile.write("{0},{1}\n".format(elapsed_seconds, y_val))
        except FileNotFoundError:
            # Occurs if file browser is canceled
            pass
        else:
            pass 
开发者ID:Roastero,项目名称:Openroast,代码行数:23,代码来源:customqtwidgets.py

示例15: _dt64_to_ordinalf

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import dates [as 别名]
def _dt64_to_ordinalf(d):
    """
    Convert `numpy.datetime64` or an ndarray of those types to Gregorian
    date as UTC float.  Roundoff is via float64 precision.  Practically:
    microseconds for dates between 290301 BC, 294241 AD, milliseconds for
    larger dates (see `numpy.datetime64`).  Nanoseconds aren't possible
    because we do times compared to ``0001-01-01T00:00:00`` (plus one day).
    """

    # the "extra" ensures that we at least allow the dynamic range out to
    # seconds.  That should get out to +/-2e11 years.
    extra = (d - d.astype('datetime64[s]')).astype('timedelta64[ns]')
    t0 = np.datetime64('0001-01-01T00:00:00', 's')
    dt = (d.astype('datetime64[s]') - t0).astype(np.float64)
    dt += extra.astype(np.float64) / 1.0e9
    dt = dt / SEC_PER_DAY + 1.0

    NaT_int = np.datetime64('NaT').astype(np.int64)
    d_int = d.astype(np.int64)
    try:
        dt[d_int == NaT_int] = np.nan
    except TypeError:
        if d_int == NaT_int:
            dt = np.nan
    return dt 
开发者ID:boris-kz,项目名称:CogAlg,代码行数:27,代码来源:dates.py


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