Ejemplo n.º 1
0
def plot_curve(dates, y, title=None):
    """
    绘制曲线
    :param dates:
    :param y:
    :return:
    """
    fig, ax = plt.subplots()
    # ax.plot(y, 'o-')
    # ax.plot(range(len(y)), y, 'o-')
    ax.plot_date(dates,
                 y,
                 marker="*",
                 linewidth=1,
                 linestyle="-",
                 color="blue")

    plt.title(title, fontproperties='SimHei', fontsize=12)
    plt.xlabel("time")
    plt.ylabel("rate")

    ### 设置X轴 ###
    ## 设置x轴范围
    # datemin = datetime.date(dates.min().year - 5, 1, 1)
    # datemax = datetime.date(dates.max().year + 5, 1, 1)
    # ax.set_xlim(datemin, datemax)

    ## 设置x轴tick和ticklabel
    # plt.xticks(np.arange(0, 50, 10), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'), rotation=90)
    # ax.set_xticks([])
    # ax.set_xticks(list(y.index))
    # ax.set_xticklabels(dates)
    # ax.set_xticklabels(["start","medium","end"])
    # ax.xaxis.set_major_formatter(NullFormatter())       # 设置x轴标签文本的格式
    # ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d'))  # 设置x轴时间标签显示格式

    # 设置主刻度标签的位置,有标签文本的格式
    ax.xaxis.set_major_locator(YearLocator(
        base=1, month=1, day=1, tz=None))  # tick every year on Feb 1st
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))  # 设置x轴标签文本的格式

    # rule = rrulewrapper(YEARLY, byeaster=1, interval=5)             # tick every 5th easter
    # ax.xaxis.set_major_locator(RRuleLocator(rule))
    # ax.xaxis.set_major_formatter(DateFormatter('%m/%d/%y'))         # 设置x轴标签文本的格式

    # 设置次刻度标签的位置,没有标签文本格式
    ax.xaxis.set_minor_locator(YearLocator())  # 将x轴次刻度标签设置为年

    ### 设置Y轴 ###
    ax.yaxis.set_major_locator(MultipleLocator(1))  # 将y轴主刻度标签设置为2的倍数
    ax.yaxis.set_major_formatter(FormatStrFormatter('%1.1f'))  # 设置y轴标签文本的格式
    ax.yaxis.set_minor_locator(MultipleLocator(0.25))  # 将此y轴次刻度标签设置为0.1的倍数

    # 打开网格
    # ax.xaxis.grid(True, which='major')  # x坐标轴的网格使用主刻度
    # ax.yaxis.grid(True, which='major')  # y坐标轴的网格使用次刻度
    ax.grid(True)
    fig.autofmt_xdate()
    plt.show()
Ejemplo n.º 2
0
def locator(span):
    if span < 400:
        return MonthLocator()
    elif 400 <= span < 800:
        return MonthLocator(bymonth=[1, 4, 7, 10])
    elif 800 <= span < 3700:
        return YearLocator()
    else:
        return YearLocator(5)
Ejemplo n.º 3
0
def plotter(cities, citytotxt):
    dates = {}
    temps = {}
    for city in cities:
        d, t = citydata(city, citytotxt)
        dates[city] = d
        temps[city] = t

    fig, ax = plt.subplots()
    legends = []
    for city in temps:
        ax.plot_date(dates[city], temps[city], '-', label=city)
        legends.append(city)
        ax.legend(legends, loc='lower left')
        ax.set_ylabel('Temperature [F]')
        ax.set_xlabel('Date')

    # Format the ticks
    years = YearLocator(2)  # major ticks every 2 years
    months = MonthLocator(
        bymonth=(1, 7))  # minor ticks every 6 months, for months 1&7
    yearsfmt = DateFormatter('%Y')
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsfmt)
    ax.xaxis.set_minor_locator(months)
    ax.autoscale_view()
    fig.autofmt_xdate()
    plt.savefig("ej6.14.png")
def fmt_major_minor(axe):
    axe.fmt_xdata = DateFormatter('%d/%m/%y %H:%M')
    x_lim = axe.get_xlim()
    if (x_lim[-1] - x_lim[0]) == 0:
        axe.xaxis.set_major_locator(HourLocator())
        axe.xaxis.set_major_formatter(DateFormatter('%d/%m/%y\n%H:%M'))
    elif 0 < (x_lim[-1] - x_lim[0]) < 5:
        axe.xaxis.set_major_locator(DayLocator())
        axe.xaxis.set_major_formatter(DateFormatter('%d/%m/%y'))
        axe.xaxis.set_minor_locator(HourLocator(byhour=(3, 6, 9, 12,
                                                        15, 18, 21)))
        axe.xaxis.set_minor_formatter(DateFormatter('%H:%M'))
    elif 5 <= (x_lim[-1] - x_lim[0]) < 11:
        axe.xaxis.set_major_locator(DayLocator())
        axe.xaxis.set_major_formatter(DateFormatter('%d/%m/%y'))
        axe.xaxis.set_minor_locator(HourLocator(byhour=(6, 12, 18)))
        axe.xaxis.set_minor_formatter(DateFormatter('%H:%M'))
    elif 11 <= (x_lim[-1] - x_lim[0]) < 45:
        axe.xaxis.set_major_locator(DayLocator(interval=3))
        axe.xaxis.set_major_formatter(DateFormatter('%d/%m/%y'))
        axe.xaxis.set_minor_locator(HourLocator(byhour=(12, 00)))
    else:
        axe.xaxis.set_minor_locator(MonthLocator())
        axe.xaxis.set_major_locator(YearLocator())
        axe.xaxis.set_major_formatter(DateFormatter('%Y'))
    for label in axe.xaxis.get_majorticklabels():
        label.set_fontsize(8)
        label.set_ha('right')
        label.set_rotation(45)
    for label in axe.xaxis.get_minorticklabels():
        label.set_fontsize(7)
        label.set_ha('right')
        label.set_rotation(45)
    for label in axe.get_yticklabels():
        label.set_fontsize(8)
Ejemplo n.º 5
0
def plotequity_trades(trades, res=None, title="Title", dataformat="%Y-%m-%d"):
    mydpi = 96
    plt.close("all")
    eq = np.cumsum(trades)
    fig = plt.figure(figsize=(1800 / mydpi, 1000 / mydpi), dpi=mydpi)

    ax = fig.add_subplot(111)
    ax.autoscale_view()

    years = YearLocator()  # every year
    months = MonthLocator()  # every month
    yearsFmt = DateFormatter('%Y')

    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)

    datemin = datetime.date(
        datetime.datetime.strptime(res.index.min(), dataformat).year, 1, 1)
    datemax = datetime.date(
        datetime.datetime.strptime(res.index.max(), dataformat).year + 1, 1, 1)

    ax.set_xlim(datemin, datemax)

    ax.fmt_xdata = DateFormatter('%Y-%m-%d')

    ax.plot(trades.index, eq.values, color="green")
    if res is not None:
        ax.plot(res.index, np.cumsum(res).values, color="black")
    fig.autofmt_xdate()
    plt.title(title)
    plt.show()
def show_plot_actual(model, dates, close_v, predicted):
    ###############################################################################
    # print trained parameters and plot
    # print("Transition matrix")
    # print(model.transmat_)
    # print()

    years = YearLocator()  # every year
    months = MonthLocator()  # every month
    yearsFmt = DateFormatter('%Y')
    fig = plt.figure()
    ax = fig.add_subplot(111)

    # for i in range(model.n_components):
    #     # use fancy indexing to plot data in each state
    #     idx = (hidden_states == i)
    #     ax.plot_date(dates[idx], close_v[idx], '--', label="%dth hidden state" % i)
    ax.plot_date(dates, close_v, '--')
    ax.legend()

    # format the ticks
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)
    ax.autoscale_view()

    # format the coords message box
    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.fmt_ydata = lambda x: '$%1.2f' % x
    ax.grid(True)

    fig.autofmt_xdate()
    plt.show()
    return 0
Ejemplo n.º 7
0
def plot_monthly(series_dates, series_record):

    series_dates = pd.to_datetime(series_dates, format="%Y-%m-%d %H:%M:%S")
    dates_list = []
    for i in series_dates:
        dates_list.append(i)

    date1 = dates_list[0]
    date2 = dates_list[len(dates_list) - 1]

    years = YearLocator()  # every year
    months = MonthLocator()  # every month
    days = DayLocator()
    dateFmt = DateFormatter('%d-%m-%Y')

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(dates_list, series_record)
    # plt.gcf().autofmt_xdate()

    # format the ticks
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(dateFmt)
    # ax.xaxis.set_minor_locator(days)
    ax.autoscale_view()

    # def price(x):
    #     return '$%1.2f' % x
    # ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    # ax.fmt_ydata = price
    # ax.grid(True)

    fig.autofmt_xdate()

    plt.show()
Ejemplo n.º 8
0
def plotPairs(df, intercept, coef):
    fig = plt.figure(figsize=(10, 5))
    gs = gridspec.GridSpec(1, 2)
    ax1 = plt.subplot(gs[0, 0])
    ax2 = plt.subplot(gs[0, 1])
    # 绘制拆线图
    ax1.plot(df.index, df.ttmpea, color='blue', label='ts_codea')
    ax1.plot(df.index, df.ttmpeb, color='yellow', label='ts_codeb')
    ax1.legend()
    # 设置X轴的刻度间隔
    # 可选:YearLocator,年刻度; MonthLocator,月刻度; DayLocator,日刻度
    ax1.xaxis.set_major_locator(YearLocator())
    # 设置X轴主刻度的显示格式
    ax1.xaxis.set_major_formatter(DateFormatter('%Y'))
    # 设置鼠标悬停时,在左下显示的日期格式
    ax1.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
    # 自动调整X轴标签角度
    fig.autofmt_xdate()

    # 绘制散点图
    ax2.scatter(df.ttmpea, df.ttmpeb)

    plt.grid(True)

    x1 = int(min(df.ttmpea))
    x2 = int(max(df.ttmpea) + 1)
    X = [x1, x2]
    y1 = intercept + x1 * coef
    y2 = intercept + x2 * coef
    Y = [y1, y2]
    ax2.plot(X, Y, color='r')
    # print('X:', X)
    # print('Y:', Y)

    plt.show()
def plot_paper_citations(paperbibcode=None, **plotkws):
    from astropy.time import Time
    from matplotlib.dates import YearLocator, MonthLocator, DateFormatter

    if paperbibcode is None:
        citations = get_paper_citations()
    else:
        citations = get_paper_citations(paperbibcode)

    datenums = np.sort([
        Time(date.replace('-00', '-01')).plot_date
        for date in citations['pubdate']
    ])

    fig = plt.gcf()
    ax = plt.gca()

    plotkws.setdefault('lw', 2)
    plotkws.setdefault('ls', '-')
    plotkws.setdefault('ms', 0)
    ax.plot_date(datenums, np.arange(len(datenums)), **plotkws)

    ax.xaxis.set_major_locator(YearLocator())
    ax.xaxis.set_major_formatter(DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(MonthLocator())
    ax.autoscale_view()

    fig.autofmt_xdate()

    plt.ylabel('# of Citations', fontsize=30)
    plt.xticks(fontsize=20)
    plt.tight_layout()

    return datenums
Ejemplo n.º 10
0
    def plot_worth_vs_time(self, names=None):
        if names is None:
            names = [
                'Investor ({:0.2f},{:0.2f})'.format(inv.buy_at, inv.sell_at)
                for inv in self.investors
            ]
        dates = [x[0] for x in self.pe_array]
        year = YearLocator()
        date_fmt = DateFormatter('%Y')
        plt.xkcd()

        # investor worth plots
        fig = plt.figure()
        ax = fig.gca()
        lines = []
        for i in range(len(self.investors)):
            result = ax.plot_date(dates, self.worth_matrix[i], '-')
            lines.append(result[0])
        ax.xaxis.set_major_locator(year)
        ax.xaxis.set_major_formatter(date_fmt)
        # ax.xaxis.set_minor_formatter(MonthLocator())
        ax.autoscale_view()
        ax.legend(lines, names, 'upper left')
        fig.autofmt_xdate()

        fig_pe = plt.figure()
        ax_pe = fig_pe.gca()
        ax_pe.plot_date(dates, [x[1] for x in self.pe_array], '-')
        ax_pe.xaxis.set_major_locator(year)
        ax_pe.xaxis.set_major_formatter(date_fmt)
        ax_pe.autoscale_view()
        ax_pe.set_title('PE Ratio vs. Time')
        fig_pe.autofmt_xdate()

        plt.show()
Ejemplo n.º 11
0
def traffic_offense_per_hour_plot(offense_per_hour):

    traffic_by_hour()
    years = YearLocator()
    month = MonthLocator()
    day_loc = DayLocator()
    hours = HourLocator()

    day_format = DateFormatter('%d%m%Y%H')

    offense_number = []
    year_of_offense = []

    fig, ax = plt.subplots()

    for dates in offense_per_hour:
        print(dates)
        offense_number.append(dates[0])
        d = datetime.datetime.strftime(dates[1], "%d%m%Y%H")
        year_of_offense.append(d)

    ax.plot_date(year_of_offense, offense_number)
    ax.set_title('Rate of Traffic Offense by Day')
    ax.xaxis.set_major_locator(day_loc)
    ax.xaxis.set_major_formatter(day_format)
    ax.xaxis.set_minor_locator(hours)
    ax.autoscale_view()

    ax.fmt_xdate = DateFormatter('%Y%m%d%H')
    ax.fmt_ydate = offense_number

    ax.grid(True)
    fig.autofmt_xdate()
    plt.show()
def plot_nino_adjusted():
    y = df['Inflation Adjusted Price']
    x = df['Date'].map(lambda x: datetime.strptime(x, '%Y-%m-%d'))
    x = np.array([x.to_pydatetime() for x in x])
    y_avg = movingaverage(y, 504)
    nino_mask = (df['ONI Index'] > 0).values

    fig = plt.figure(figsize=(14, 8))
    ax = fig.add_subplot(1, 1, 1)
    loc = YearLocator(5)
    plt.tick_params(axis='both', which='major', labelsize=11)
    ax.plot(x, y, color='gray', alpha=.6, label='Inflation Adjusted Price')
    ax.plot(x[252:-252],
            y_avg[252:-252],
            color='r',
            alpha=.7,
            label='2-Year Moving Average')
    ax.fill_between(x,
                    np.zeros(len(x)),
                    y,
                    where=nino_mask,
                    alpha=.6,
                    label='El Nino Years')
    ax.xaxis.set_major_locator(loc)
    plt.suptitle('Corn Prices Over Time:\n1959 - 2016', size=20, alpha=.8)
    plt.ylabel('Inflation Adjusted\nPrice of Nearest Futures Contract ($)',
               size=14,
               labelpad=30)
    plt.legend()
    # plt.show()
    plt.savefig('Figures/inflation_adjusted_nino.png')
Ejemplo n.º 13
0
def main(sta1, sta2, filterid, components, mov_stack=1, show=True, outfile=None):
    db = connect()
    components_to_compute = get_components_to_compute(db)
    maxlag = float(get_config(db,'maxlag'))
    cc_sampling_rate = float(get_config(db,'cc_sampling_rate'))
    start, end, datelist = build_movstack_datelist(db)
    # mov_stack = get_config(db,"mov_stack")
 
   
    plt.figure(figsize=(16,16))
    sta1 = sta1.replace('.','_')
    sta2 = sta2.replace('.','_')
    if sta2 > sta1: # alphabetical order filtering!
        pair = "%s:%s"%(sta1,sta2)
        
        print "New Data for %s-%s-%i-%i"%(pair,components,filterid, mov_stack)
        format = "matrix"
        nstack, stack_total = get_results(db,sta1,sta2,filterid,components,datelist,mov_stack, format=format)
        # vmax = scoreatpercentile(np.abs(stack_total[np.isnan(stack_total)==False]) , 98)
        # for i in range(stack_total.shape[0]):
            # if not np.all( np.isnan(stack_total[i,:])):
                # print np.max(stack_total[i,:])
                # stack_total[i,:] /= np.max(stack_total[i,:])
        # stack_total /= np.max(stack_total, axis=0)
        xextent = (date2num(start), date2num(end),-maxlag,maxlag)
        ax = plt.subplot(111)
        plt.imshow(stack_total.T, extent=xextent, aspect="auto",interpolation='none',origin='lower',cmap='seismic',
                vmin=-1e-2,vmax=1e-2)
        plt.ylabel("Lag Time (s)")
        plt.axhline(0,lw=0.5,c='k')
        plt.grid()

        ax.xaxis.set_major_locator( YearLocator() )
        ax.xaxis.set_major_formatter(  DateFormatter('%Y-%m') )

        # ax.xaxis.set_minor_locator( MonthLocator(interval=2) )
        # ax.xaxis.set_minor_formatter(  DateFormatter('%Y-%m-%d') )
        
        lag = 120
        plt.ylim(-lag,lag)
        plt.title('%s : %s'%(sta1,sta2))
        name = '%i.%s_%s.png'%(filterid,sta1,sta2)

        #~ plt.savefig('interfero_publi.png',dpi=300)
        # plt.figure()
        # maxx = np.argmax(stack_total, axis=0)
        # plt.plot(maxx)
        
        if outfile:
            if outfile.startswith("?"):
                pair = pair.replace(':','-')
                outfile = outfile.replace('?', '%s-%s-f%i-m%i' % (pair,
                                                                  components,
                                                                  filterid,
                                                                  mov_stack))
            outfile = "interferogram " + outfile
            print "output to:", outfile
            plt.savefig(outfile)
        if show:
            plt.show()
Ejemplo n.º 14
0
    def plot_all_states(self):
        years = YearLocator()   # every year
        months = MonthLocator()  # every month
        yearsFmt = DateFormatter('%Y')
        fig = plt.figure(figsize=(20,10))
        ax = fig.add_subplot(111)

        ax.plot(self.dates, self.fracChange, 'g-', alpha=.4)

        for i in range(self.model.n_components):
            # use fancy indexing to plot data in each state
            idx = (self.hidden_states == i)
            ax.plot_date(self.dates[idx], self.fracChange[idx], 'o', label="hidden state $\# %d$" % i)
    
        ax.legend()

        # format the ticks
        ax.xaxis.set_major_locator(years)
        ax.xaxis.set_major_formatter(yearsFmt)
        ax.xaxis.set_minor_locator(months)
        ax.autoscale_view()

        # format the coords message box
        ax.fmt_xdata = DateFormatter('%Y-%m-%d')
        ax.fmt_ydata = lambda x: '$%1.2f' % x
        ax.grid(True)

        fig.autofmt_xdate()
        plt.title('fracChange by GHMM Hidden States predicted on stock %s\
\n from %s to %s' % (self.symbol.upper(), self.fr_date, self.to_date))
        plt.show()
Ejemplo n.º 15
0
def plot_in_sample_hidden_states(hmm_model, df, series):
    """
    Plot the adjusted closing prices masked by 
    the in-sample hidden states as a mechanism
    to understand the market regimes.
    """
    # Predict the hidden states array
    hidden_states = hmm_model.predict(df)
    # Create the correctly formatted plot
    fig, axs = plt.subplots(hmm_model.n_components,
                            sharex=True,
                            sharey=True,
                            figsize=[20, 20])
    colours = cm.rainbow(np.linspace(0, 1, hmm_model.n_components))
    for i, (ax, colour) in enumerate(zip(axs, colours)):
        mask = hidden_states == i
        ax.plot_date(df.index[mask],
                     series[mask],
                     ".",
                     linestyle='none',
                     c=colour)
        ax.set_title("Hidden State #%s" % i)
        ax.xaxis.set_major_locator(YearLocator())
        ax.xaxis.set_minor_locator(MonthLocator())
        ax.grid(True)
    plt.show()
Ejemplo n.º 16
0
def applyTicks(axs, days, stop):
    for ax in axs:
        month = MonthLocator()
        year = YearLocator()
        day = DayLocator()
        day2 = DayLocator(bymonthday=1)
        # rrule = RRuleLocator()
        if days < 100:
            fmt1 = DateFormatter('week %W')
            week = WeekdayLocator()
            ax.xaxis.set_major_locator(week)
            ax.xaxis.set_major_formatter(fmt1)
        else:
            fmt2 = DateFormatterEx()
            ax.xaxis.set_major_locator(day2)
            ax.xaxis.set_major_formatter(fmt2)


        ax.xaxis.set_minor_locator(day)
        # ax.xaxis.set_minor_formatter(fmt2)

    for ax in axs:
        ax.axhline(y=0, lw=1.0)

        # ax.axvline(x=pd.to_datetime(stop+STARTUNIXTIME, unit="s"), lw=1.0)
        ax.axvline(x=pd.to_datetime(STARTUNIXTIME, unit="s"), lw=1.0)

        ax.set_xlim(pd.to_datetime(STARTUNIXTIME, unit="s"), pd.to_datetime(stop+STARTUNIXTIME-3600*24*7, unit="s"))


        for item in ([ax.xaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()):
            item.set_fontsize(32)
Ejemplo n.º 17
0
def make_line_plot(
    ax,
    df,
    x_col,
    y_col,
    title='',
    ylabel='',
    xlabel='',
):

    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    if x_col == 'Date':
        dates = [
            datetime.datetime.strptime(x, "%Y-%m-%d").date() for x in df[x_col]
        ]
        for col in y_col:
            ax.plot(dates, df[col], label=col)
        years = YearLocator()
        months = MonthLocator()
        yearsFmt = DateFormatter('%Y')
        ax.xaxis.set_major_locator(years)
        ax.xaxis.set_major_formatter(yearsFmt)
        ax.xaxis.set_minor_locator(months)
        ax.fmt_xdata = DateFormatter(yearsFmt)
    else:
        for col in y_col:
            ax.plot(df[x_col], df[col], label=col)

    if len(y_col) > 1:
        ax.legend(bbox_to_anchor=(1.05, 1))
Ejemplo n.º 18
0
def plot_date_format(ax, time_range=None, locator=None, time_format=None):
    ''' This function formats plots by plt.plot_date

    Input:
        ax: plotting axis
        time_range: a tuple of two datetime objects indicating xlim. e.g., (dt.date(1991,1,1), dt.date(1992,12,31))
        locator: time locator on the plot; 'year' for year; 'month' for month. e.g., ('month', 3) for plot one tick every 3 months
        time_format: a string of time format, e.g. '%Y/%m'
    '''

    import matplotlib.pyplot as plt
    import datetime as dt
    from matplotlib.dates import YearLocator, MonthLocator, DateFormatter

    # Plot time range
    if time_range != None:
        plt.xlim(time_range[0], time_range[1])

    # Set time locator (interval)
    if locator != None:
        if locator[0] == 'year':
            ax.xaxis.set_major_locator(YearLocator(locator[1]))
        elif locator[0] == 'month':
            ax.xaxis.set_major_locator(MonthLocator(interval=locator[1]))

    # Set time ticks format
    if time_format != None:
        ax.xaxis.set_major_formatter(DateFormatter(time_format))

    return ax
    def _show_plot(self, dates, close_v, hidden_states, title):
        years = YearLocator()  # every year
        months = MonthLocator()  # every month
        yearsFmt = DateFormatter('%Y/%m')
        fig = plt.figure()
        ax = fig.add_subplot(111)
        fig.canvas.set_window_title(title)

        value = hidden_states
        ax.plot_date(dates, close_v, '-', label="Actual value")
        ax.plot_date(dates, value, '-', label="Predicted value")

        ax.legend()

        # format the ticks
        ax.xaxis.set_major_formatter(yearsFmt)
        ax.autoscale_view()

        # format the coords message box
        ax.fmt_xdata = DateFormatter('%Y-%m-%d')
        # ax.fmt_ydata = lambda x: '$%1f' % x
        ax.grid(True)

        fig.autofmt_xdate()
        plt.savefig('plot.png')
        plt.show()

        error = np.sum(np.abs((close_v - hidden_states) * 1.0 /
                              close_v)) * 100.0 / close_v.shape[0]
        return error
Ejemplo n.º 20
0
def plotequity_pred(pred, res, title, dataformat="%Y-%m-%d"):
    mydpi = 96
    plt.close("all")
    pos = np.where(pred > 0, 1, np.where(pred < -0, -1, 0))
    eq = np.cumsum(pos * res)
    fig = plt.figure(figsize=(1800 / mydpi, 1000 / mydpi), dpi=mydpi)

    ax = fig.add_subplot(111)
    ax.autoscale_view()

    print(res.head())

    years = YearLocator()  # every year
    months = MonthLocator()  # every month
    yearsFmt = DateFormatter('%Y')

    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)

    datemin = datetime.date(
        datetime.datetime.strptime(res.index.min(), dataformat).year, 1, 1)
    datemax = datetime.date(
        datetime.datetime.strptime(res.index.max(), dataformat).year + 1, 1, 1)

    ax.set_xlim(datemin, datemax)

    ax.fmt_xdata = DateFormatter('%Y-%m-%d')

    ax.plot(res.index, eq.values, color="green")
    ax.plot(res.index, np.cumsum(res).values, color="black")
    fig.autofmt_xdate()
    plt.title(title)
    plt.show()
def plot_corn_prices_adjusted():
    y = df['Inflation Adjusted Price']
    x = df['Date'].map(lambda x: datetime.strptime(x, '%Y-%m-%d'))
    corn_syrup = datetime(1970, 1, 1)
    e85 = datetime(2000, 1, 1)
    y_avg = movingaverage(y, 504)

    fig = plt.figure(figsize=(14, 8))
    ax = fig.add_subplot(1, 1, 1)
    loc = YearLocator(5)
    ax.plot(x, y, color='gray', alpha=.6, label='Inflation Adjusted Price')
    ax.plot(x[252:-252],
            y_avg[252:-252],
            color='r',
            alpha=.7,
            label='2-Year Moving Average')
    ax.plot((corn_syrup, corn_syrup), (0, 1500), color='k')
    ax.plot((e85, e85), (0, 1500), color='k')
    ax.xaxis.set_major_locator(loc)
    plt.tick_params(axis='both', which='major', labelsize=11)
    plt.text(corn_syrup + timedelta(days=100), 50,
             'Corn Syrup\'s\nCommerical Introduction')
    plt.text(e85 + timedelta(days=100), 50, 'E85 Becomes\nWidely Used')
    plt.suptitle('Corn Prices Over Time:\n1959 - 2016', size=20, alpha=.8)
    plt.ylabel('Inflation Adjusted\nPrice of Nearest Futures Contract ($)',
               size=14,
               labelpad=30)
    plt.legend()
    # plt.show()
    plt.savefig('Figures/inflation_adjusted_demand_shocks.png')
Ejemplo n.º 22
0
def plot_timeline_sentinel(gf):
    """Plot dinosar inventory acquisitions as a timeline.

    Parameters
    ----------
    gf :  GeoDataFrame
        A geopandas GeoDataFrame

    """
    dfA = gf.query('platform == "Sentinel-1A"')
    dfAa = dfA.query(' flightDirection == "ASCENDING" ')
    dfAd = dfA.query(' flightDirection == "DESCENDING" ')
    dfB = gf.query('platform == "Sentinel-1B"')
    dfBa = dfB.query(' flightDirection == "ASCENDING" ')
    dfBd = dfB.query(' flightDirection == "DESCENDING" ')

    # Same colors as map
    orbits = gf.relativeOrbit.unique()
    colors = plt.cm.jet(np.linspace(0, 1, orbits.size))

    fig, ax = plt.subplots(figsize=(11, 8.5))
    plt.scatter(dfAa.timeStamp.values,
                dfAa.orbitCode.values,
                edgecolors=colors[dfAa.orbitCode.values],
                facecolors='None',
                cmap='jet',
                s=60,
                label='Asc S1A')
    plt.scatter(dfBa.timeStamp.values,
                dfBa.orbitCode.values,
                edgecolors=colors[dfBa.orbitCode.values],
                facecolors='None',
                cmap='jet',
                s=60,
                marker='d',
                label='Asc S1B')
    plt.scatter(dfAd.timeStamp.values,
                dfAd.orbitCode.values,
                c=colors[dfAd.orbitCode.values],
                cmap='jet',
                s=60,
                label='Dsc S1A')
    plt.scatter(dfBd.timeStamp.values,
                dfBd.orbitCode.values,
                c=colors[dfBd.orbitCode.values],
                cmap='jet',
                s=60,
                marker='d',
                label='Dsc S1B')

    plt.yticks(gf.orbitCode.unique(), gf.relativeOrbit.unique())

    ax.xaxis.set_minor_locator(MonthLocator())
    ax.xaxis.set_major_locator(YearLocator())
    plt.legend(loc='lower right')
    plt.ylim(-1, orbits.size)
    plt.ylabel('Orbit Number')
    fig.autofmt_xdate()
    plt.title('Acquisition Timeline')
    plt.savefig('timeline.pdf', bbox_inches='tight')
Ejemplo n.º 23
0
def test_date_demo1():

    years = YearLocator()  # every year
    months = MonthLocator()  # every month
    yearsFmt = DateFormatter('%Y')
    
    # make file paths OS independent
    infile = os.path.join('examples','data','yahoofinance-INTC-19950101-20040412.csv')
    quotes = pd.read_csv(infile,index_col=0,parse_dates=True,infer_datetime_format=True)
    
    dates = quotes.index
    opens = quotes['Open']
    
    fig, ax = plt.subplots()
    ax.plot_date(dates, opens, '-')
    
    # format the ticks
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)
    ax.autoscale_view()
    
    
    # format the coords message box
    def price(x):
        return '$%1.2f' % x
    
    
    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.fmt_ydata = price
    ax.grid(True)
    
    fig.autofmt_xdate()
    buf = io.BytesIO()
    plt.savefig(buf)
Ejemplo n.º 24
0
    def _create_xaxis_date(self, ax, date_index):
        """  Uses buest guess for x axis labels """
        window = (date_index[-1] - date_index[0]).astype(int)

        interval = 5

        xlabel = ""
        if window <= 3600:
            minor_locator = MinuteLocator(interval=interval)
            minor_formatter = DateFormatter("%M")
            major_locator = HourLocator()
            major_formatter = DateFormatter("\n%Y-%m-%d %H:%M")
            xlabel = "Minute"
        elif window <= 86400:
            minor_locator = HourLocator(interval=interval)
            minor_formatter = DateFormatter("%H:%M")
            major_locator = DayLocator()
            major_formatter = DateFormatter("\n%Y-%m-%d")
            xlabel = "Hour"
        elif window <= (7 * 86400):
            minor_locator = HourLocator(interval=6)
            minor_formatter = DateFormatter("%H:%M")
            major_locator = DayLocator()
            major_formatter = DateFormatter("\n%Y-%m-%d")
            xlabel = "Hour"
        elif window <= (60 * 86400):
            #if len(date_index) > 30:
            #    interval = 2
            minor_locator = DayLocator(interval=interval)
            minor_formatter = DateFormatter("%m-%d")
            major_locator = YearLocator()
            major_formatter = DateFormatter("\n%Y")
            xlabel = "Day"
        else:
            minor_locator = MonthLocator(interval=interval)
            minor_formatter = DateFormatter("%B")
            major_locator = YearLocator()
            major_formatter = DateFormatter("\n%Y")
            xlabel = "Month"

        ax.xaxis.set_minor_locator(minor_locator)
        ax.xaxis.set_minor_formatter(minor_formatter)
        ax.xaxis.set_major_locator(major_locator)
        ax.xaxis.set_major_formatter(major_formatter)
        ax.fmt_xdata = DateFormatter("%Y-%m-%d %H:%M:%S")

        ax.set_xlabel(xlabel)
Ejemplo n.º 25
0
def plot_timeline_table(gf):
    """Plot dinosar inventory acquisitions as a timeline with a table.

    Parameters
    ----------
    gf :  GeoDataFrame
        A geopandas GeoDataFrame

    """
    dfA = gf.query('platform == "Sentinel-1A"')
    dfAa = dfA.query(' flightDirection == "ASCENDING" ')
    dfAd = dfA.query(' flightDirection == "DESCENDING" ')
    dfB = gf.query('platform == "Sentinel-1B"')
    dfBa = dfB.query(' flightDirection == "ASCENDING" ')
    dfBd = dfB.query(' flightDirection == "DESCENDING" ')

    # summary table
    dfS = gpd.pd.DataFrame(index=gf.relativeOrbit.unique())
    dfS['Start'] = gf.groupby('relativeOrbit').sceneDateString.min()
    dfS['Stop'] = gf.groupby('relativeOrbit').sceneDateString.max()
    dfS['Dates'] = gf.groupby('relativeOrbit').sceneDateString.nunique()
    dfS['Frames'] = gf.groupby('relativeOrbit').sceneDateString.count()
    dfS['Direction'] = gf.groupby('relativeOrbit').flightDirection.first()
    dfS['UTC'] = gf.groupby('relativeOrbit').utc.first()
    dfS.sort_index(inplace=True, ascending=False)
    dfS.index.name = 'Orbit'

    # Same colors as map
    orbits = gf.relativeOrbit.unique()
    colors = plt.cm.jet(np.linspace(0, 1, orbits.size))

    fig, ax = plt.subplots(figsize=(11, 8.5))
    plt.scatter(dfAa.timeStamp.values, dfAa.orbitCode.values,
                c=colors[dfAa.orbitCode.values], cmap='jet',
                s=60, facecolor='none', label='S1A')
    plt.scatter(dfBa.timeStamp.values, dfBa.orbitCode.values,
                c=colors[dfBa.orbitCode.values], cmap='jet',
                s=60, facecolor='none', marker='d', label='S1B')
    plt.scatter(dfAd.timeStamp.values, dfAd.orbitCode.values,
                c=colors[dfAd.orbitCode.values], cmap='jet',
                s=60, label='S1A')
    plt.scatter(dfBd.timeStamp.values, dfBd.orbitCode.values,
                c=colors[dfBd.orbitCode.values], cmap='jet',
                s=60, marker='d', label='S1B')

    plt.yticks(gf.orbitCode.unique(), gf.relativeOrbit.unique())

    table(ax, dfS, loc='top', zorder=10, fontsize=12,
          cellLoc='center', rowLoc='center',
          bbox=[0.1, 0.7, 0.6, 0.3])  # [left, bottom, width, height])

    ax.xaxis.set_minor_locator(MonthLocator())
    ax.xaxis.set_major_locator(YearLocator())
    plt.legend(loc='upper right')
    plt.ylim(-1, orbits.size+3)
    plt.ylabel('Orbit Number')
    fig.autofmt_xdate()
    plt.title('Sentinel-1 timeline')
    plt.savefig('timeline_with_table.pdf', bbox_inches='tight')
Ejemplo n.º 26
0
def prettify_ax(ax, title="", center=False, percentage=False, start_date=config.start_date, end_date=config.end_date):
    """Makes matplotlib.pyplot.Axes look pretty

    Parameters:
        ax : Axes
        title : str
        center : bool
            x axis in center of graph instead of bottom
        start_date : date, optional
        end_date : date, optional
    """

    if title != "":
        ax.set_title(title)
    ax.set_xlabel("Date")
    ax.set_ylabel("Price")
    ax.legend(loc="upper left", fontsize="small", labelspacing=0.2)
    '''
    matplotlib.rcParams["legend.loc"] = "upper left"  # matplotlib.rc("legend", loc="upper left")
    matplotlib.pyplot.rcParams["legend.fontsize"] = "small"  # matplotlib.pyplot.rc("legend", fontsize="small")
    matplotlib.pyplot.rcParams["legend.labelspacing"] = 0.2  # matplotlib.pyplot.rc("legend", labelspacing=0.2)
    '''

    # ax.spines["top"].set_visible(False)
    # ax.spines["right"].set_visible(False)

    ax.xaxis.set_major_locator(YearLocator())
    ax.xaxis.set_minor_locator(MonthLocator((1, 7)))
    ax.xaxis.set_major_formatter(DateFormatter("\n%Y"))
    ax.xaxis.set_minor_formatter(DateFormatter("%b"))

    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    # ax.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on")  # Remove the tick marks

    # TODO: what causes smooshing
    # ax.set_xlim(start_date, end_date)  # this stops smooshing
    ax.margins(x=0)

    min_x = ax.get_xlim()[0].astype(int)
    max_x = ax.get_xlim()[1].astype(int)

    if not center and ax.get_ylim()[0] < 0:
        ax.set_ylim(ymin=0)
    if center:
        min_y = ax.get_ylim()[0].astype(float)
        max_y = ax.get_ylim()[1].astype(float)
        if abs(min_y) != abs(max_y):
            ax.set_ylim(ymin=-max(abs(min_y), abs(max_y)), ymax=max(abs(min_y), abs(max_y)))
        ax.plot(range(min_x, max_x), [0] * len(range(min_x, max_x)), "-", linewidth=0.5, color="black")
    if percentage:
        ax.set_ylim(ymin=0, ymax=100)
        # ax.yaxis.set_ticks(np.arange(0, 100, 10))
        # ax.set_yticks([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

    # TODO: do this for the dates too. Have to get locators, since there are too many ticks
    # for y in range(ax.get_ylim()[0], ax.get_ylim()[1], 10):
    for i, y in enumerate(ax.get_yticks().astype(float)[1:-1]):
        ax.plot(range(min_x, max_x), [y] * len(range(min_x, max_x)), "--", linewidth=0.5, color="black", alpha=config.alpha)
Ejemplo n.º 27
0
 def _plot_balance(self, _):
     ax = pl.gca()
     formatter = DateFormatter("%Y-%m-%d")
     ax.xaxis.set_major_formatter(formatter)
     ax.xaxis.set_major_locator(MonthLocator())
     ax.xaxis.set_minor_locator(YearLocator())
     pl.plot(*MODEL.balance_data())
     pl.gcf().autofmt_xdate()
     pl.show()
Ejemplo n.º 28
0
def Draw_Z_Index_Graph(outfile, strdate, data):

    fig = plt.figure(figsize=(8,5))
    ax = fig.add_subplot(111)
    # plt.plot(strdate, data, '*', color = 'black', lw = 0.8)

    plt.plot(strdate, data[53519], '.', marker ='.',color='k', lw = 0.8, label = u"惠农")
    plt.plot(strdate, data[53612], '.', marker ='^',color='r', lw = 0.8, label = u"吴忠")
    plt.plot(strdate, data[53614], '.', marker ='D',color='g', lw = 0.8, label = u"银川")
    plt.plot(strdate, data[53615], '.', marker ='+',color='b', lw = 0.8, label = u"陶乐")
    plt.plot(strdate, data[53704], '.', marker ='x',color='c', lw = 0.8, label = u"中卫")
    plt.plot(strdate, data[53705], '.', marker ='*',color='y', lw = 0.8, label = u"中宁")
    plt.plot(strdate, data[53723], '.', marker ='s',color='m', lw = 0.8, label = u"盐池")
    plt.plot(strdate, data[53806], '.', marker ='8',color='gold', lw = 0.8, label = u"海源")
    plt.plot(strdate, data[53810], '.', marker ='p',color='peru', lw = 0.8, label = u"同心")
    plt.plot(strdate, data[53817], '.', marker ='h',color='brown', lw = 0.8, label = u"固原")
    plt.plot(strdate, data[53903], '.', marker ='v',color='wheat', lw = 0.8, label = u"西吉")
    plt.plot(strdate, data[53910], '.', marker ='.',color='tan', lw = 0.8, label = u"六盘山")

    ##获取时间轴的起始、结束时间
    s = np.int(strdate[0].strftime('%Y'))
    e = np.int(strdate[-1].strftime('%Y'))

    if (s % 10) > 5:
        syear = s / 10 * 10 + 5
    else:
        syear = s / 10 * 10

    if (e % 10) > 5:
        eyear = e / 10 * 10 + 10
    else:
        eyear = e / 10 * 10 + 5

    xstart = datetime.datetime.strptime(str(syear), '%Y')
    xend = datetime.datetime.strptime(str(eyear), '%Y')

    # 绘制一次拟合线性趋势线

    ax.set_xlim(xstart, xend)
    # ax.set_ylim(150, 450)

    formatter = DateFormatter('%Y')
    ax.xaxis.set_major_locator(formatter)
    ax.xaxis.set_major_locator(YearLocator(base=5))
    # ax.set_xlabel(str, fontsize=14)
    # ax.xaxis.set_label_coords(0.75, -2.5)


    plt.title(u'Z指数时间序列图', fontproperties=font, fontsize=12)

    ax.set_xlabel(u'年   份', fontproperties=font, fontsize=10)
    # ax.set_ylabel(u'降水量/mm', fontproperties=font, fontsize=10)
    ax.legend(loc='upper right', prop=font, fontsize=6, edgecolor ='white')
    # plt.savefig(outfile, dpi=200, bbox_to_anchor='tight')

    plt.show()
Ejemplo n.º 29
0
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
Ejemplo n.º 30
0
def plot_graph(people, overall, output, individuals):
    # i dunno what this stuff is but it makes the graph happen

    years = YearLocator()   # every year
    months = MonthLocator()  # every month
    yearsFmt = DateFormatter('%Y-%m')

    fig, ax = plt.subplots(figsize=(16,12), dpi=80)

    fig.suptitle('#PLACEHOLDER activity per day', fontsize=20)
    
    legend = []

    if individuals:
        top_talkers = sorted(people, reverse=True, key=lambda k: people[k]['msgcount'])[:individuals]
        for person in top_talkers:
            (p_dates, p_activity) = build_date_arrays(people[person]['dates'])
            print("plotting {}'s activity: {} lines".format(person, people[person]['msgcount']))
            ax.plot_date(p_dates, p_activity, '-')
            legend.append(person)
            
            #print(str(people[person]['dates']))
            #print(str(p_activity))
            #i = 0
            #while i < len(p_dates):
            #    print("{}: {}".format(str(p_dates[i]), p_activity[i]))
            #    i += 1
            #print(str(p_dates))
            #break
    else:
        (o_dates,o_activity) = build_date_arrays(overall)
        ax.plot_date(o_dates, o_activity, '-')
        legend.append('Overall')

    # TODO figure out how to show individual months along the x axis, right now it's kinda bare

    plt.legend(legend, loc='upper right')
    #ax.set_yscale('log') # doesn't work as well as i'd hoped :(
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)
    ax.autoscale_view()

    ax.fmt_xdata = DateFormatter("%Y-%m-%d")
    ax.grid(True)

    fig.autofmt_xdate()

    if output == 'x11':
        plt.show()
    else:
        filename = 'ircstatter_{}.png'.format(time.strftime('%Y-%m-%d_%H:%M:%S'))
        plt.savefig(filename)
        print('graph saved as {}'.format(filename))