Python matplotlib.dates() Examples

The following are 30 code examples of matplotlib.dates(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib , or try the search function .
Example #1
Source File: dates.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: check_dam_talk_plot.py    From hydrology with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: dates.py    From neural-network-animation with MIT License 6 votes vote down vote up
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)) 
Example #4
Source File: dates.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: dates.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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)) 
Example #6
Source File: nupic_anomaly_output.py    From ecg-htm with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: dates.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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)) 
Example #8
Source File: dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #9
Source File: dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #10
Source File: dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #11
Source File: nupic_output.py    From nupic.critic with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #12
Source File: nupic_output.py    From nupic.critic with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #13
Source File: nupic_output.py    From nupic.critic with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #14
Source File: nupic_output.py    From nupic.critic with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #15
Source File: plotting.py    From REDPy with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #16
Source File: StockTradingGraph.py    From Stock-Trading-Visualization with MIT License 6 votes vote down vote up
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([]) 
Example #17
Source File: StockTradingGraph.py    From Stock-Trading-Visualization with MIT License 6 votes vote down vote up
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) 
Example #18
Source File: stochastic_volatility.py    From numpyro with Apache License 2.0 6 votes vote down vote up
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]) 
Example #19
Source File: customqtwidgets.py    From Openroast with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #20
Source File: dates.py    From coffeegrindsize with MIT License 6 votes vote down vote up
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)) 
Example #21
Source File: dates.py    From coffeegrindsize with MIT License 6 votes vote down vote up
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)) 
Example #22
Source File: dates.py    From coffeegrindsize with MIT License 6 votes vote down vote up
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) 
Example #23
Source File: dates.py    From CogAlg with MIT License 6 votes vote down vote up
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 
Example #24
Source File: dates.py    From CogAlg with MIT License 6 votes vote down vote up
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)) 
Example #25
Source File: dates.py    From CogAlg with MIT License 6 votes vote down vote up
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)) 
Example #26
Source File: dates.py    From CogAlg with MIT License 6 votes vote down vote up
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) 
Example #27
Source File: dates.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
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, six.string_types):
        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)) 
Example #28
Source File: dates.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
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)) 
Example #29
Source File: PriceTradeAnalyzer.py    From Stock-Price-Trade-Analyzer with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #30
Source File: dates.py    From neural-network-animation with MIT License 5 votes vote down vote up
def __call__(self, x, pos=0):
        if x == 0:
            raise ValueError('DateFormatter found a value of x=0, which is '
                             'an illegal date.  This usually occurs because '
                             'you have not informed the axis that it is '
                             'plotting dates, e.g., with ax.xaxis_date()')
        dt = num2date(x, self.tz)
        return self.strftime(dt, self.fmt)