Python matplotlib.dates.date2num() Examples

The following are 30 code examples of matplotlib.dates.date2num(). 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.dates , or try the search function .
Example #1
Source File: chart.py    From XQuant with MIT License 7 votes vote down vote up
def _candlestick_ax(df, ax):
    quotes = df.reset_index()
    quotes.loc[:, 'datetime'] = mdates.date2num(quotes.loc[:, 'datetime'].astype(dt.date))
    fplt.candlestick_ohlc(ax, quotes.values, width=0.4, colorup='red', colordown='green') 
Example #2
Source File: monitor_tick_main.py    From InplusTrader_Linux with MIT License 6 votes vote down vote up
def __loadTicksFromMongo(self,host,port,dbName,symbolName,startDatetimeStr,endDatetimeStr):
        """mid
        加载mongodb数据转换并返回数字格式的时间及价格
        """
        mongoConnection = MongoClient( host=host,port=port)
        collection = mongoConnection[dbName][symbolName]   

        startDate = dt.datetime.strptime(startDatetimeStr, '%Y-%m-%d %H:%M:%S')
        endDate = dt.datetime.strptime(endDatetimeStr, '%Y-%m-%d %H:%M:%S')  
        cx = collection.find({'datetime': {'$gte': startDate, '$lte': endDate}})    
        
        tickDatetimeNums = []
        tickPrices = []
        for d in cx:
            tickDatetimeNums.append(mpd.date2num(d['datetime']))
            tickPrices.append(d['lastPrice'])
        return tickDatetimeNums,tickPrices
    
    #---------------------------------------------------------------------- 
Example #3
Source File: chart.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _process_hist(self, hist):
        """
        Get data from histogram, including bin_ranges and values.
        """
        self.cyclic = hist.get_dimension(0).cyclic
        x = hist.kdims[0]
        edges = hist.interface.coords(hist, x, edges=True)
        values = hist.dimension_values(1)
        hist_vals = np.array(values)
        xlim = hist.range(0)
        ylim = hist.range(1)
        is_datetime = isdatetime(edges)
        if is_datetime:
            edges = np.array([dt64_to_dt(e) if isinstance(e, np.datetime64) else e for e in edges])
            edges = date2num(edges)
            xlim = tuple(dt_to_int(v, 'D') for v in xlim)
        widths = np.diff(edges)
        return edges[:-1], hist_vals, widths, xlim+ylim, is_datetime 
Example #4
Source File: DailyDifferenceAverageSpark.py    From incubator-sdap-nexus with Apache License 2.0 6 votes vote down vote up
def toImage(self):
        from StringIO import StringIO
        import matplotlib.pyplot as plt
        from matplotlib.dates import date2num

        times = [date2num(datetime.fromtimestamp(dayavglistdict[0]['time'], pytz.utc).date()) for dayavglistdict in
                 self.results()]
        means = [dayavglistdict[0]['mean'] for dayavglistdict in self.results()]
        plt.plot_date(times, means, '|g-')

        plt.xlabel('Date')
        plt.xticks(rotation=70)
        plt.ylabel(u'Difference from 5-Day mean (\u00B0C)')
        plt.title('Sea Surface Temperature (SST) Anomalies')
        plt.grid(True)
        plt.tight_layout()

        sio = StringIO()
        plt.savefig(sio, format='png')
        return sio.getvalue() 
Example #5
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 #6
Source File: test_dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _test_date2num_dst(date_range, tz_convert):
    # Timezones
    BRUSSELS = dateutil.tz.gettz('Europe/Brussels')
    UTC = mdates.UTC

    # Create a list of timezone-aware datetime objects in UTC
    # Interval is 0b0.0000011 days, to prevent float rounding issues
    dtstart = datetime.datetime(2014, 3, 30, 0, 0, tzinfo=UTC)
    interval = datetime.timedelta(minutes=33, seconds=45)
    interval_days = 0.0234375   # 2025 / 86400 seconds
    N = 8

    dt_utc = date_range(start=dtstart, freq=interval, periods=N)
    dt_bxl = tz_convert(dt_utc, BRUSSELS)

    expected_ordinalf = [735322.0 + (i * interval_days) for i in range(N)]
    actual_ordinalf = list(mdates.date2num(dt_bxl))

    assert actual_ordinalf == expected_ordinalf 
Example #7
Source File: LiCSBAS_plot_ts.py    From LiCSBAS with GNU General Public License v3.0 6 votes vote down vote up
def tim_slidupdate(val):
        global cum_disp_flag
        timein = tslider.val
        timenearest = np.argmin(np.abs(mdates.date2num(imdates_dt)-timein))
        dstr = imdates_dt[timenearest].strftime('%Y/%m/%d')
#        axv.set_title('Time = %s'%(dstr))
        axv.set_title('%s (Ref: %s)'%(dstr, dstr_ref))
        newv = (cum[timenearest, :, :]-cum_ref)*mask
        newv = newv-np.nanmean(newv[refy1:refy2, refx1:refx2])
            
        cax.set_data(newv)
        cax.set_cmap(cmap)
        cax.set_clim(dmin, dmax)
        cbr.set_label('mm')
        cum_disp_flag = True

        pv.canvas.draw() 
Example #8
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 #9
Source File: figures.py    From NowTrade with MIT License 6 votes vote down vote up
def __init__(self, dataset, rows=1, grid=True):
        # We need to handle a strategy being passed
        if isinstance(dataset, strategy.Strategy):
            self.strategy = dataset
            self.data_frame = self.strategy.dataset.data_frame
            self.realtime_data_frame = dataset.realtime_data_frame
        else: # Assume a dataset was passed
            self.strategy = None
            self.data_frame = dataset.data_frame
            self.realtime_data_frame = None
        self.data_frame.reset_index(inplace=True)
        date_conversion = lambda date: date2num(date.to_pydatetime())
        self.data_frame['DATE'] = self.data_frame['Date'].apply(date_conversion)
        self.rows = rows
        if grid:
            plt.rc('axes', grid=True)
            plt.rc('grid', color='0.75', linestyle='-', linewidth='0.2')
        self.current_figure = None
        self.figure_first_ax = None
        self.figure_rows = 1
        self.legend = []
        self.legend_labels = []
        self.add_figure(self.rows)
        self.logger = logger.Logger(self.__class__.__name__)
        self.logger.info('dataset: %s  rows: %s  grid: %s' %(dataset, rows, grid)) 
Example #10
Source File: usingFloat2extracCls4.py    From Ocean-Data-Map-Project with GNU General Public License v3.0 6 votes vote down vote up
def readGiopsIce(lat,lon,datenum):
    di = 0            
    for datei in datenum:
        print datei 
        dt0= datetime.strptime(datei, "%Y-%m-%d %H:%M:%S")
        dt1 = mdates.date2num(dt0)
#        dt2 = mdates.num2date(dt1)
        
#        print dt0,dt2
#        taxis.append(dt1)        
        
        dayStr = str(dt0.year)+str(dt0.month).rjust(2,'0')+str(dt0.day).rjust(2,'0')
#        print dayStr
        
        ficePath = "/home/xuj/work/project/novaFloat/iceData/"
        
        fname = ficePath+"giops_"+dayStr+"00_ice.nc"
        
        cfile = Dataset(fname,'r')
        
        aice = np.squeeze(cfile.variables["aice"][0,:,:])
        
    

    return giopsIce 
Example #11
Source File: callprotocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_command(self, ser,command,eol,hex=False):
            if hex:
                command = self.hexify_command(command,eol)
            else:
                command = eol+command+eol
            #print 'Command:  %s \n ' % command.replace(eol,'')
            sendtime = date2num(datetime.utcnow())
            #print "Sending"
            ser.write(command)
            #print "Received something - interpretation"
            response = self.lineread(ser,eol)
            #print "interprete", response
            receivetime = date2num(datetime.utcnow())
            meantime = np.mean([receivetime,sendtime])
            #print "Timediff", (receivetime-sendtime)*3600*24
            return response, num2date(meantime).replace(tzinfo=None) 
Example #12
Source File: collectormethods.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def interprete_data(payload, ident, stream, sensorid):
    """
    source:mqtt:
    """
    lines = payload.split(';') # for multiple lines send within one payload
    # allow for strings in payload !!
    array = [[] for elem in KEYLIST]
    keylist = identifier[sensorid+':keylist']
    multilist = identifier[sensorid+':multilist']
    for line in lines:
        data = line.split(',')
        timear = list(map(int,data[:7]))
        #log.msg(timear)
        time = datetime(timear[0],timear[1],timear[2],timear[3],timear[4],timear[5],timear[6])
        array[0].append(date2num(time))
        for idx, elem in enumerate(keylist):
            index = KEYLIST.index(elem)
            if not elem.endswith('time'):
                if elem in NUMKEYLIST:
                    array[index].append(float(data[idx+7])/float(multilist[idx]))
                else:
                    array[index].append(data[idx+7])

    return np.asarray([np.asarray(elem) for elem in array]) 
Example #13
Source File: _converter.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _dt_to_float_ordinal(dt):
    """
    Convert :mod:`datetime` to the Gregorian date as UTC float days,
    preserving hours, minutes, seconds and microseconds.  Return value
    is a :func:`float`.
    """
    if (isinstance(dt, (np.ndarray, Index, ABCSeries)
                   ) and is_datetime64_ns_dtype(dt)):
        base = dates.epoch2num(dt.asi8 / 1.0E9)
    else:
        base = dates.date2num(dt)
    return base


# Datetime Conversion 
Example #14
Source File: test_dates.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_date_date2num_numpy(t0, dtype):
    time = mdates.date2num(t0)
    tnp = np.array(t0, dtype=dtype)
    nptime = mdates.date2num(tnp)
    assert np.array_equal(time, nptime) 
Example #15
Source File: _converter.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _dt_to_float_ordinal(dt):
    """
    Convert :mod:`datetime` to the Gregorian date as UTC float days,
    preserving hours, minutes, seconds and microseconds.  Return value
    is a :func:`float`.
    """
    if (isinstance(dt, (np.ndarray, Index, ABCSeries)
                   ) and is_datetime64_ns_dtype(dt)):
        base = dates.epoch2num(dt.asi8 / 1.0E9)
    else:
        base = dates.date2num(dt)
    return base


# Datetime Conversion 
Example #16
Source File: stock_analysis.py    From intro_ds with Apache License 2.0 5 votes vote down vote up
def transFeature(data):
    """
    提取特征,5日收益率,20日收益率,5日成交量增长率以及20日成交量增长率
    """
    data[["amount", "close_price"]] = data[["amount", "close_price"]].apply(pd.to_numeric)
    data["a_5"] = np.log(data["amount"]).diff(-5)
    data["a_20"] = np.log(data["amount"]).diff(-20)
    data["r_5"] = np.log(data["close_price"]).diff(-5)
    data["r_20"] = np.log(data["close_price"]).diff(-20)
    data["date2num"] = data["date"].apply(lambda x: date2num(datetime.strptime(x, "%Y-%m-%d")))
    data = data[data["date"] > "2005-06-01"]
    return data 
Example #17
Source File: _converter.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def autoscale(self):
        """
        Set the view limits to include the data range.
        """
        dmin, dmax = self.datalim_to_dt()
        if dmin > dmax:
            dmax, dmin = dmin, dmax

        # We need to cap at the endpoints of valid datetime

        # TODO(wesm): unused?

        # delta = relativedelta(dmax, dmin)
        # try:
        #     start = dmin - delta
        # except ValueError:
        #     start = _from_ordinal(1.0)

        # try:
        #     stop = dmax + delta
        # except ValueError:
        #     # The magic number!
        #     stop = _from_ordinal(3652059.9999999)

        dmin, dmax = self.datalim_to_dt()

        vmin = dates.date2num(dmin)
        vmax = dates.date2num(dmax)

        return self.nonsingular(vmin, vmax) 
Example #18
Source File: _converter.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _convert_1d(values, unit, axis):
        def try_parse(values):
            try:
                return _dt_to_float_ordinal(tools.to_datetime(values))
            except Exception:
                return values

        if isinstance(values, (datetime, pydt.date)):
            return _dt_to_float_ordinal(values)
        elif isinstance(values, np.datetime64):
            return _dt_to_float_ordinal(lib.Timestamp(values))
        elif isinstance(values, pydt.time):
            return dates.date2num(values)
        elif (is_integer(values) or is_float(values)):
            return values
        elif isinstance(values, compat.string_types):
            return try_parse(values)
        elif isinstance(values, (list, tuple, np.ndarray, Index)):
            if isinstance(values, Index):
                values = values.values
            if not isinstance(values, np.ndarray):
                values = com._asarray_tuplesafe(values)

            if is_integer_dtype(values) or is_float_dtype(values):
                return values

            try:
                values = tools.to_datetime(values)
                if isinstance(values, Index):
                    values = _dt_to_float_ordinal(values)
                else:
                    values = [_dt_to_float_ordinal(x) for x in values]
            except Exception:
                values = _dt_to_float_ordinal(values)

        return values 
Example #19
Source File: stock_analysis.py    From intro_ds with Apache License 2.0 5 votes vote down vote up
def drawData(ax, _data):
    """
    使用柱状图表示股市数据
    """
    candlestick_ochl(ax,
        _data[["date2num", "open_price", "close_price", "high_price", "low_price"]].values,
        colorup="r", colordown="g", width=0.5)
    ax.xaxis.set_major_locator(YearLocator())
    ax.xaxis.set_major_formatter(DateFormatter('%Y'))
    return ax 
Example #20
Source File: preproccess_binclass.py    From Using-Deep-Learning-Neural-Networks-and-Candlestick-Chart-Representation-to-Predict-Stock-Market with MIT License 5 votes vote down vote up
def createLabel(fname, seq_len):
    print("Creating label . . .")
    filename = fname.split('/')
    removeOutput("{}_label_{}.txt".format(filename[1][:-4], seq_len))

    df = pd.read_csv(fname, parse_dates=True, index_col=0)
    df.fillna(0)

    df.reset_index(inplace=True)
    df['Date'] = df['Date'].map(mdates.date2num)
    for i in range(0, len(df)):
        c = df.ix[i:i + int(seq_len), :]
        starting = 0
        endvalue = 0
        label = ""

        if len(c) == int(seq_len) + 1:
            for idx, val in enumerate(c['Close']):
                if idx == 0:
                    starting = float(val)
                if idx == len(c) - 1:
                    endvalue = float(val)
            if endvalue > starting:
                label = 1
            else:
                label = 0
            with open("{}_label_{}.txt".format(filename[1][:-4], seq_len), 'a') as the_file:
                the_file.write("{}-{},{}".format(filename[1][:-4], i, label))
                the_file.write("\n")
    print("Create label finished.") 
Example #21
Source File: nupic_output.py    From nupic.critic with GNU Affero General Public License v3.0 5 votes vote down vote up
def write(self, timestamps, actualValues, predictedValues,
            predictionStep=1):

    assert len(timestamps) == len(actualValues) == len(predictedValues)

    # We need the first timestamp to initialize the lines at the right X value,
    # so do that check first.
    if not self.linesInitialized:
      self.initializeLines(timestamps)

    for index in range(len(self.names)):
      self.dates[index].append(timestamps[index])
      # self.convertedDates[index].append(date2num(timestamps[index]))
      self.actualValues[index].append(actualValues[index])
      self.predictedValues[index].append(predictedValues[index])

      # Update data
      self.actualLines[index].set_xdata(self.dates[index])
      self.actualLines[index].set_ydata(self.actualValues[index])
      self.predictedLines[index].set_xdata(self.dates[index])
      self.predictedLines[index].set_ydata(self.predictedValues[index])

      self.graphs[index].relim()
      self.graphs[index].autoscale_view(True, True, True)

    plt.draw()
    plt.legend(('actual','predicted'), loc=3) 
Example #22
Source File: uiBasicWidget.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def initHistoricalData(self, symbol):
        """初始历史数据"""
        d = {}
        cx = self.mainEngine.dbQuery(MINUTE_DB_NAME, symbol, d)

        if cx:
            for data in cx:
                date = datetime.strptime(data['date'], "%Y%m%d")
                n = date2num(date)
                o = data['open']             # OHLC
                h = data['high']
                l = data['low']
                c = data['close']
                oi = data['openInterest']

                self.listBar.append((n, o, c, l, h))
                self.listOpen.append(o)
                self.listClose.append(c)
                self.listHigh.append(h)
                self.listLow.append(l)
                self.listOpenInterest.append(oi)

        self.initCompleted = True    # 读取历史数据完成
        print "initCompleted!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        self.plotKline()     # K线图

    #---------------------------------------------------------------------- 
Example #23
Source File: plot.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def candlestick_ochl(ax, quotes, width=0.2, colorup='r', colordown='g', alpha=1.0):

    """
    Plot the time, open, close, high, low as a vertical line ranging
    from low to high.  Use a rectangular bar to represent the
    open-close span.  If close >= open, use colorup to color the bar,
    otherwise use colordown

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    quotes : sequence of (time, open, close, high, low, ...) sequences
        As long as the first 5 elements are these values,
        the record can be as long as you want (e.g., it may store volume).

        time must be in float days format - see date2num

    width : float
        fraction of a day for the rectangle width
    colorup : color
        the color of the rectangle where close >= open
    colordown : color
         the color of the rectangle where close <  open
    alpha : float
        the rectangle alpha level

    Returns
    -------
    ret : tuple
        returns (lines, patches) where lines is a list of lines
        added and patches is a list of the rectangle patches added

    """
    return _candlestick(ax, quotes, width=width, colorup=colorup,
                        colordown=colordown,
                        alpha=alpha, ochl=True) 
Example #24
Source File: plot.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def plot_day_summary_ohlc(ax, quotes, ticksize=3, colorup='r', colordown='g', ):
    """Plots day summary

        Represent the time, open, high, low, close as a vertical line
        ranging from low to high.  The left tick is the open and the right
        tick is the close.



    Parameters
    ----------
    ax : `Axes`
        an `Axes` instance to plot to
    quotes : sequence of (time, open, high, low, close, ...) sequences
        data to plot.  time must be in float date format - see date2num
    ticksize : int
        open/close tick marker in points
    colorup : color
        the color of the lines where close >= open
    colordown : color
        the color of the lines where close <  open

    Returns
    -------
    lines : list
        list of tuples of the lines added (one tuple per quote)
    """
    return _plot_day_summary(ax, quotes, ticksize=ticksize,
                     colorup=colorup, colordown=colordown,
                     ochl=False) 
Example #25
Source File: plot.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def plot_day_summary_oclh(ax, quotes, ticksize=3, colorup='r', colordown='g', ):
    """Plots day summary

        Represent the time, open, close, high, low as a vertical line
        ranging from low to high.  The left tick is the open and the right
        tick is the close.



    Parameters
    ----------
    ax : `Axes`
        an `Axes` instance to plot to
    quotes : sequence of (time, open, close, high, low, ...) sequences
        data to plot.  time must be in float date format - see date2num
    ticksize : int
        open/close tick marker in points
    colorup : color
        the color of the lines where close >= open
    colordown : color
        the color of the lines where close <  open

    Returns
    -------
    lines : list
        list of tuples of the lines added (one tuple per quote)
    """
    return _plot_day_summary(ax, quotes, ticksize=ticksize,
                     colorup=colorup, colordown=colordown,
                     ochl=True) 
Example #26
Source File: element.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _set_axis_limits(self, axis, view, subplots, ranges):
        """
        Compute extents for current view and apply as axis limits
        """
        # Extents
        extents = self.get_extents(view, ranges)
        if not extents or self.overlaid:
            axis.autoscale_view(scalex=True, scaley=True)
            return

        valid_lim = lambda c: util.isnumeric(c) and not np.isnan(c)
        coords = [coord if np.isreal(coord) or isinstance(coord, np.datetime64) else np.NaN for coord in extents]
        coords = [date2num(util.dt64_to_dt(c)) if isinstance(c, np.datetime64) else c
                  for c in coords]
        if self.projection == '3d' or len(extents) == 6:
            l, b, zmin, r, t, zmax = coords
            if self.invert_zaxis or any(p.invert_zaxis for p in subplots):
                zmin, zmax = zmax, zmin
            if zmin != zmax:
                if valid_lim(zmin):
                    axis.set_zlim(bottom=zmin)
                if valid_lim(zmax):
                    axis.set_zlim(top=zmax)
        else:
            l, b, r, t = coords

        if self.invert_axes:
            l, b, r, t = b, l, t, r

        invertx = self.invert_xaxis or any(p.invert_xaxis for p in subplots)
        xlim, scalex = self._compute_limits(l, r, self.logx, invertx, 'left', 'right')
        inverty = self.invert_yaxis or any(p.invert_yaxis for p in subplots)
        ylim, scaley =  self._compute_limits(b, t, self.logy, inverty, 'bottom', 'top')
        if xlim:
            axis.set_xlim(**xlim)
        if ylim:
            axis.set_ylim(**ylim)
        axis.autoscale_view(scalex=scalex, scaley=scaley) 
Example #27
Source File: nupic_output.py    From nupic.critic with GNU Affero General Public License v3.0 5 votes vote down vote up
def write(self, timestamps, actualValues, predictedValues,
            predictionStep=1):

    assert len(timestamps) == len(actualValues) == len(predictedValues)

    # We need the first timestamp to initialize the lines at the right X value,
    # so do that check first.
    if not self.linesInitialized:
      self.initializeLines(timestamps)

    for index in range(len(self.names)):
      self.dates[index].append(timestamps[index])
      # self.convertedDates[index].append(date2num(timestamps[index]))
      self.actualValues[index].append(actualValues[index])
      self.predictedValues[index].append(predictedValues[index])

      # Update data
      self.actualLines[index].set_xdata(self.dates[index])
      self.actualLines[index].set_ydata(self.actualValues[index])
      self.predictedLines[index].set_xdata(self.dates[index])
      self.predictedLines[index].set_ydata(self.predictedValues[index])

      self.graphs[index].relim()
      self.graphs[index].autoscale_view(True, True, True)

    plt.pause(0.000001) # This also calls draw()
    plt.legend(('actual','predicted'), loc=3) 
Example #28
Source File: plotting.py    From japandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _make_plot(self):
        try:
            from pandas.plotting._timeseries import (_decorate_axes,
                                                     format_dateaxis)
        except ImportError:
            from pandas.tseries.plotting import _decorate_axes, format_dateaxis
        plotf = self._get_plot_function()
        ax = self._get_ax(0)

        data = self.data
        data.index.name = 'Date'
        data = data.to_period(freq=self.freq)
        index = data.index
        data = data.reset_index(level=0)

        if self._is_ts_plot():
            data['Date'] = data['Date'].apply(lambda x: x.ordinal)
            _decorate_axes(ax, self.freq, self.kwds)
            candles = plotf(data, ax, **self.kwds)
            format_dateaxis(ax, self.freq, index)
        else:
            from matplotlib.dates import date2num, AutoDateFormatter, AutoDateLocator

            data['Date'] = data['Date'].apply(lambda x: date2num(x.to_timestamp()))
            candles = plotf(data, ax, **self.kwds)

            locator = AutoDateLocator()
            ax.xaxis.set_major_locator(locator)
            ax.xaxis.set_major_formatter(AutoDateFormatter(locator))

        return candles 
Example #29
Source File: _converter.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def autoscale(self):
        """
        Set the view limits to include the data range.
        """
        dmin, dmax = self.datalim_to_dt()
        if dmin > dmax:
            dmax, dmin = dmin, dmax

        # We need to cap at the endpoints of valid datetime

        # TODO(wesm): unused?

        # delta = relativedelta(dmax, dmin)
        # try:
        #     start = dmin - delta
        # except ValueError:
        #     start = _from_ordinal(1.0)

        # try:
        #     stop = dmax + delta
        # except ValueError:
        #     # The magic number!
        #     stop = _from_ordinal(3652059.9999999)

        dmin, dmax = self.datalim_to_dt()

        vmin = dates.date2num(dmin)
        vmax = dates.date2num(dmax)

        return self.nonsingular(vmin, vmax) 
Example #30
Source File: _converter.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _convert_1d(values, unit, axis):
        def try_parse(values):
            try:
                return _dt_to_float_ordinal(tools.to_datetime(values))
            except Exception:
                return values

        if isinstance(values, (datetime, pydt.date)):
            return _dt_to_float_ordinal(values)
        elif isinstance(values, np.datetime64):
            return _dt_to_float_ordinal(tslibs.Timestamp(values))
        elif isinstance(values, pydt.time):
            return dates.date2num(values)
        elif (is_integer(values) or is_float(values)):
            return values
        elif isinstance(values, compat.string_types):
            return try_parse(values)
        elif isinstance(values, (list, tuple, np.ndarray, Index, ABCSeries)):
            if isinstance(values, ABCSeries):
                # https://github.com/matplotlib/matplotlib/issues/11391
                # Series was skipped. Convert to DatetimeIndex to get asi8
                values = Index(values)
            if isinstance(values, Index):
                values = values.values
            if not isinstance(values, np.ndarray):
                values = com.asarray_tuplesafe(values)

            if is_integer_dtype(values) or is_float_dtype(values):
                return values

            try:
                values = tools.to_datetime(values)
                if isinstance(values, Index):
                    values = _dt_to_float_ordinal(values)
                else:
                    values = [_dt_to_float_ordinal(x) for x in values]
            except Exception:
                values = _dt_to_float_ordinal(values)

        return values