當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。