Exemplo n.º 1
0
 def plot(self, name='wikipgs'):
     fraction = 1
     width = 512
     fig, ax = plt.subplots(figsize=set_size(width, fraction),
                            sharex='all',
                            gridspec_kw={'hspace': 0.5})
     #plt.plot(self.uncertainty, color='green', alpha=0.9)
     #plt.plot(self.y50,alpha=0.8, label='ofat')
     plt.plot(self.y_test, alpha=0.8, label='gt')
     plt.plot(self.yqcnn, alpha=0.8, label='qcnn')
     plt.plot(self.ycnn, alpha=0.8, label='cnn')
     plt.plot(self.yqclnn, alpha=0.8, label='qconvl')
     plt.plot(self.yqlstm[1], alpha=0.8, label='qlstm')
     plt.plot(self.ylstm, alpha=0.6, label='lstm')
     ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.0f'))
     ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.0f'))
     ax.xaxis.set_major_locator(plt.LinearLocator(6))
     ax.yaxis.set_major_locator(plt.LinearLocator(6))
     plt.legend(loc='upper right',
                bbox_to_anchor=(1.01, 1.05),
                ncol=3,
                columnspacing=0.5)
     plt.xlabel('Time (days)')
     #print('{} smae: {} std: {}'.format(name, self.smae, self.std_s))
     plt.ylabel('Daily page visits')
     plt.tight_layout()
Exemplo n.º 2
0
    def _save(self, name='wiki1'):
        '''

        Parameters
        ----------
        name : TYPE, optional
            DESCRIPTION. The default is 'wiki1'.

        Returns
        -------
        None.

        '''
        fraction = 1
        width = 212
        fig, ax = plt.subplots(figsize=set_size(width, fraction),
                               sharex='all',
                               gridspec_kw={'hspace': 0.5})
        #plt.plot(self.y10, color='green', alpha=0.9)
        plt.plot(self.y50, color='red', alpha=0.8, label='OFAT')
        plt.plot(self.y_test, color='olive', alpha=0.8, label='ground truth')
        ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2f'))
        ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.0f'))
        ax.xaxis.set_major_locator(plt.LinearLocator(6))
        ax.yaxis.set_major_locator(plt.LinearLocator(6))
        plt.legend(loc='upper right', bbox_to_anchor=(1.0, 1.05), ncol=2)
        plt.xlabel('Time (days)')
        #print('{} smae: {} std: {}'.format(name, self.smae, self.std_s))
        plt.ylabel('Weekly prices')
        plt.tight_layout()
        plt.savefig('../../ofat/figures/' + name + '.pdf',
                    format='pdf',
                    bbox_inches='tight')
Exemplo n.º 3
0
def partDescriptorSize(title=False, filename=None, show=False):
    smallX, smallY = splitIntoXY(data.DATA_300x300["descriptorPartSize"])
    mediumX, mediumY = splitIntoXY(data.DATA_640x480["descriptorPartSize"])
    largeX, largeY = splitIntoXY(data.DATA_1280x720["descriptorPartSize"])

    fig, (top, upper, middle, bottom) = plt.subplots(4, 1, sharex=True, figsize=PICTURE_SIZE)

    if title:
        bottom.set_title("Průměrná velikost deskriptoru části", fontsize="xx-large")

    fig.text(0.04, 0.55, "Průměrná velikost deskriptoru části (v tisících)", va="center", rotation="vertical", fontsize="xx-large")

    setupXAxis(bottom)

    for axis in [top, bottom, middle, upper]:
        for tick in axis.get_yticklabels():
            tick.set_fontsize("x-large")

    bottom.set_ylim(0, 8000)
    middle.set_ylim(10000, 30000)
    middle.xaxis.tick_top()
    upper.set_ylim(40000, 60000)
    upper.xaxis.tick_top()
    top.set_ylim(100000, 104000)
    top.xaxis.tick_top()

    # up to 3 bars (sizes), 0.8 is default and leaves a little room between algorithms
    barWidth = 0.8 / 3
    hW = barWidth / 2

    bottom.yaxis.set_major_formatter(FuncFormatter(SECOND_THOUSAND_FORMATTER))
    middle.yaxis.set_major_formatter(FuncFormatter(SECOND_THOUSAND_FORMATTER))
    upper.yaxis.set_major_formatter(FuncFormatter(SECOND_THOUSAND_FORMATTER))
    top.yaxis.set_major_formatter(FuncFormatter(SECOND_THOUSAND_FORMATTER))

    bottom.yaxis.set_major_locator(plt.LinearLocator(5))
    middle.yaxis.set_major_locator(plt.LinearLocator(5))
    upper.yaxis.set_major_locator(plt.LinearLocator(5))
    top.yaxis.set_major_locator(plt.LinearLocator(5))

    drawAcross([bottom, middle], smallX - 2 * hW, smallY, barWidth, color=pickColors(COLORS_300x300, smallX), edgecolor="black")
    drawAcross([bottom, middle, upper], mediumX, mediumY, barWidth, color=pickColors(COLORS_640x480, mediumX), edgecolor="black")
    drawAcross([bottom, middle, upper, top], largeX + 2 * hW, largeY, barWidth, color=pickColors(COLORS_1280x720, largeX), edgecolor="black")

    middle.legend(loc="center left", bbox_to_anchor=(1.0125, 1), handles=GRAY_LEGEND, fontsize='large')
    bottom.grid(True, axis="y")
    middle.grid(True, axis="y")
    upper.grid(True, axis="y")
    top.grid(True, axis="y")

    drawAxisSplitters(bottom, middle, upper, top)

    topMargin = TOP_MARGIN_TITLE if title else TOP_MARGIN_NO_TITLE
    plt.subplots_adjust(**transformMargins(top=topMargin, pictureSize=PICTURE_SIZE, **DEFAULT_MARGINS), hspace=0.25)

    if filename:
        plt.savefig(os.path.abspath(f"{OUTPUT_DIR}/{filename}"))
    if show:
        plt.show()
Exemplo n.º 4
0
 def plotuncertanty(self, name='preduncer'):
     fraction = 0.5
     width = 510
     timex = 2000
     y = np.concatenate((self.y_train[-timex:], self.yqcnn), axis=0)
     #self.y_test[91]=9.06
     fig, ax = plt.subplots(figsize=set_size(width, fraction), sharey='all')
     #plt.plot(self.y_train[-timex:],'grey', label='fitted model')
     plt.plot(y + 0.1, 'red', label='ground truth', alpha=0.9)
     ax.fill_between(range(timex,
                           len(self.y_test) + timex),
                     self.yqcnnl,
                     self.yqcnnu - 0.5,
                     color='royalblue',
                     alpha=0.5,
                     label='predictive uncertainty')
     plt.plot(range(timex,
                    len(self.y_test) + timex),
              self.y_test + 0.1,
              'orange',
              label='fitted model',
              alpha=0.8)
     ax.axvline(x=timex,
                ymin=0,
                ymax=5,
                color='grey',
                ls='--',
                lw=2,
                alpha=0.7)
     #plt.scatter(timex+91, self.y_test[91], marker='*', s=70, color='red', label='predicted extreme event')#extreme event
     #ax.grid(True, zorder=5)
     #plt.plot(self.y_test, color='olive', alpha=0.8, label ='ground truth')
     #plt.plot(range(timex,len(self.y_test)+timex), self.yqlstm[0],color='grey',alpha=0.3)
     #plt.plot(range(timex,len(self.y_test)+timex), self.yqlstm[2],color='grey',alpha=0.3)
     plt.ylim([8.8, 10.2])
     ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2f'))
     ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.0f'))
     ax.xaxis.set_major_locator(plt.LinearLocator(6))
     ax.yaxis.set_major_locator(plt.LinearLocator(6))
     plt.legend(loc='upper right',
                bbox_to_anchor=(0.75, 1.03),
                ncol=1,
                columnspacing=0.05)
     ax.set_xlabel('Time ')
     ax.set_ylabel(r'EDF stock price (\pounds)')
     plt.tight_layout()
     plt.savefig('../_8th/myphd/thesis_1/figures/' + name + '.pdf',
                 format='pdf',
                 bbox_inches='tight')
Exemplo n.º 5
0
def plot(input_folder, plot_point_count, points_per_pixel,
         not_normalized_gradient):
    _, gray, scene = read_input(input_folder)

    pyramid = calc_pyramid(gray, PYRAMID_LVL_COUNT, 2)
    center_point = scene.model.vector6
    deltas = [calc_translation_delta(scene.mesh.vertices)] * 3 + \
             [ANGLE_DELTA_IN_DEGREES] * 3

    for image in pyramid:
        integral_calculator = IntegralCalculator(image, scene,
                                                 points_per_pixel,
                                                 not not_normalized_gradient)
        for axis in xrange(6):
            limits = (center_point[axis] - deltas[axis],
                      center_point[axis] + deltas[axis])
            plot_data = build_plot_data(integral_calculator, center_point,
                                        axis, limits, plot_point_count)
            plt.subplot(231 + axis)
            plt.grid(True)
            plt.xlabel(X_LABELS[axis], fontsize='x-large')
            plt.xlim(*limits)
            plt.gca().xaxis.set_major_locator(plt.LinearLocator(3))
            plt.plot(*plot_data)

    plt.tight_layout(pad=0.1, w_pad=0.1, h_pad=0.1)
    plt.show()
Exemplo n.º 6
0
def plot(bench, filename):
    def function(x1, x2):
        vec = bench.function()
        return vec(2, [x1, x2])

    plotN = 100
    x1 = np.linspace(bench.Lower, bench.Upper, plotN)
    x2 = np.linspace(bench.Lower, bench.Upper, plotN)

    x1, x2 = np.meshgrid(x1, x2)

    vecFunction = np.vectorize(function)
    z = vecFunction(x1, x2)

    fig = plt.figure()

    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x1,
                           x2,
                           z,
                           rstride=1,
                           cstride=1,
                           cmap=plt.cm.rainbow,
                           linewidth=0,
                           antialiased=False)
    fig.colorbar(surf, shrink=0.5, aspect=7, cmap=plt.cm.coolwarm)

    ax.zaxis.set_major_locator(plt.LinearLocator(10))
    ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.01f'))

    plt.savefig(filename)
Exemplo n.º 7
0
def plot_cost_function(cost_function, x_range, y_range, resolution, point1, point2):
    x = np.arange(x_range[0], x_range[1], resolution)
    y = np.arange(y_range[0], y_range[1], resolution)

    X, Y = np.meshgrid(x, y)
    Z = np.vectorize(cost_function)(X, Y)

    fig = plt.figure()
    fig.suptitle(r'Cost function with $\theta = 0$')
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.RdBu, linewidth=0, antialiased=False)
    ax.zaxis.set_major_locator(plt.LinearLocator(10))
    ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.02f'))

    ax.set_xlabel('x-position')
    ax.set_ylabel('y-position')
    ax.set_zlabel('cost function')
    ax.view_init(elev=25, azim=-120)

    fig.colorbar(surf, shrink=0.5, aspect=5)

    # Plot 2D
    fig = plt.figure()
    im = plt.imshow(Z, cmap=plt.cm.RdBu)
    cset = plt.contour(Z, [cost_function(point1[0], point1[1]), cost_function(point2[0], point2[1])],
                       linewidths=2, cmap=plt.cm.Set2)
    plt.clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
    plt.colorbar(im)
Exemplo n.º 8
0
def plot_HessD(fig, arr, subx1, suby2, subsize, extent, interpolation, title,
               xlabel, ylabel):
    cm = makecmap(arr)
    #cm.set_gamma(0.2)
    ax = fig.add_axes([subx1, suby2, subsize, subsize])
    ax.imshow(arr,
              cmap=cm,
              aspect='auto',
              extent=extent,
              interpolation=interpolation)
    ax.set_title(title, fontsize=11)
    ax.set_xlabel(xlabel, fontsize=11)
    ax.set_ylabel(ylabel, fontsize=11)
    ax.set_xticklabels(ax.get_xticks(), size=11)
    ax.set_yticklabels(ax.get_yticks(), size=11)
    #cax = fig.add_axes([subx1+0.13, suby2+0.35, subsize-0.15, subsize-0.365])
    cax = fig.add_axes(
        [subx1 + 0.03, suby2 + 0.35, subsize - 0.20, subsize - 0.365])
    cb_arr = np.linspace(arr.min(), arr.max(), 1e2).reshape(1, 1e2)
    cax_limits = [np.floor(arr.min()), np.ceil(arr.max()), 0, 1]
    cax.imshow(cb_arr,
               cmap=cm,
               aspect='auto',
               extent=cax_limits,
               interpolation='nearest')
    cax.plot([arr.min(), arr.min()], [0, 1], 'k-')
    cax.plot([arr.max(), arr.max()], [0, 1], 'w-')
    cax.axis(cax_limits)
    cax.yaxis.set_visible(False)
    cax.xaxis.tick_bottom()
    cax.xaxis.set_major_locator(plt.LinearLocator(5))
    cax.set_xticklabels(cax.get_xticks(), size=8)
    #cax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
    return ax, cax
Exemplo n.º 9
0
Arquivo: run.py Projeto: yusme/DDPG
def plot_function_countur3D(min, max, action, episode):
    x = np.arange(min, max, 0.025)
    y = np.arange(min, max, 0.025)
    # meshgrid create a matrix von min to max with 0.1 as distance
    # the output is 2 matrix where one is the transport of the other one
    X, Y = pyl.meshgrid(x, y)
    #Z=z_function(X,np.transpose(X))
    Z = action
    print Y
    #==========
    #  3D
    #==========
    fig = plt.figure()
    #plt.ion()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(Y,
                           X,
                           Z,
                           rstride=1,
                           cstride=1,
                           cmap=plt.cm.RdBu,
                           linewidth=0,
                           antialiased=False)
    ax.set_xlim([min, max])
    ax.set_ylim([min, max])
    ax.zaxis.set_major_locator(plt.LinearLocator(3))
    ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.02f'))
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show(False)
    plt.draw()
    name_file = 'exp/episode3D' + str(episode) + '.png'
    print name_file.__str__()
    plt.savefig(name_file.__str__())
    plt.close()
Exemplo n.º 10
0
def plot_prediction(y, predictions, title):
    total_days = [datetime.date(2021, 1, 1) + datetime.timedelta(days=int(i)) for i in range(int(y.shape[0]) + predictions.shape[0])]

    if config['time'] >= config['update_data']:
        today = str(datetime.date.today())
        last_day = str(datetime.date.today() + datetime.timedelta(days=config['days_to_forecast']))
    else:
        today = str(datetime.date.today() - datetime.timedelta(1))
        last_day = str(datetime.date.today() - datetime.timedelta(1) + datetime.timedelta(days=config['days_to_forecast']))

    final_dates = []
    for i in total_days:
        i = str(i)
        final_dates.append(i[5:])

    y = np.array(y)
    y = y.reshape((y.shape[0]), 1)
    predictions = np.array(predictions)
    predictions = predictions.reshape((predictions.shape[0]), 1)

    series = np.concatenate([y, predictions], axis=0)

    #old = load_predictions(title)

    fig, ax = plt.subplots(figsize=(15, 8))
    ax.plot(final_dates, series, label='Predicted cases')
    ax.plot(y, color='red', label='Verified cases')
    fig.autofmt_xdate()
    plt.gca().xaxis.set_major_locator(plt.LinearLocator(numticks=30))
    ax.axvspan(today[5:], last_day[5:], alpha=0.25)
    plt.title(title)
    plt.legend()
    plt.grid()
    plt.show()
    fig.savefig(path_img + title.replace(" ", "") + ".png")
Exemplo n.º 11
0
def plot_figs(fig_num, elev, azim, a):
    fig = plt.figure(fig_num, figsize=(4, 3))
    plt.clf()
    ax = Axes3D(fig, elev=elev, azim=azim)

    ax.scatter(body_mass, work_level, heat_output, c='k', marker='+')
   
    X = np.arange(55, 85, 0.5)
    Y = np.arange(90, 180, 0.5)
    X, Y = np.meshgrid(X, Y)
    Z = a[0] + a[1]*X + +(Y/(a[2]+a[3]*X))
    ax.plot_surface(X, Y, Z,alpha=.5, antialiased=True,rstride=200, cstride=100, cmap=plt.cm.coolwarm)
             
    ax.set_xlabel('BODY_MASS', color='b')
    ax.set_ylabel('WORK_LEVEL', color='b')
    ax.set_zlabel('HEAT_OUTPUT', color='b')
    
    ax.w_xaxis.set_ticklabels([])
    ax.w_yaxis.set_ticklabels([])
    ax.w_zaxis.set_ticklabels([])
    
    ax.zaxis.set_major_locator(plt.LinearLocator(10))  
    ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.f'))
    ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.f'))
    ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.f'))
Exemplo n.º 12
0
def plot_HessD(fig, arr, subx1, suby2, subsize, extent, cmin, cmax,
               interpolation, title, xlabel, ylabel, col_bool):
    if col_bool:
        cm = matplotlib.cm.jet  #makecmap(arr)
        nm = None
        cmap_ofs = 0.
    else:
        cm = makecmap(arr)
        nm = None
        cmap_ofs = 0.05
    #cm.set_gamma(0.2)
    ax = fig.add_axes([subx1, suby2, subsize, subsize])
    #Change cm to gist_yarg if you want grayscale
    ax.imshow(arr,
              cmap=cm,
              aspect='auto',
              extent=extent,
              interpolation=interpolation,
              norm=nm,
              clim=(cmin, cmax))
    ax.set_title(title, fontsize=8)
    ax.set_xlabel(xlabel, fontsize=8)
    ax.set_ylabel(ylabel, fontsize=8)
    ax.get_xticks()
    #ax.set_xticklabels(ax.get_xticks(), size=8)
    #ax.set_yticklabels(ax.get_yticks(), size=8)
    lowx = extent[0] * 0.9
    highx = extent[1] * 0.7
    #ax.set_xlim(np.array(extent[0])-lowx, np.array(extent[1])-highx)
    ax.set_ylim(maxdepth + .1, mindepth + 1)
    #ax.set_xlim(lowx, highx)
    ax.set_xlim(minshift + .3, maxshift - 1)
    #ax.set_xticks(np.array([-1, 0, 1, 2, 3]))
    #ax.set_xticklabels(np.array([-1.0, 0, 1.0, 2.0, 3.0]), size = 8)
    ax.set_yticklabels(ax.get_yticks(), size=8)
    ax.set_xticklabels(ax.get_xticks(), size=8)
    #cax = fig.add_axes([subx1+0.13, suby2+0.35, subsize-0.15, subsize-0.365])
    cax = fig.add_axes([
        subx1 + 0.07 + cmap_ofs, suby2 + 0.225, subsize - 0.10 - cmap_ofs,
        subsize - 0.235
    ])
    cb_arr = np.linspace(arr.min(), arr.max(), 100).reshape(1, 100)
    cax_limits = [np.floor(arr.min()), np.ceil(arr.max()), 0, 1]
    #Change cmap = cm to cmap = 'gist_yarg' if you want grayscale
    cax.imshow(cb_arr,
               cmap=cm,
               aspect='auto',
               extent=cax_limits,
               interpolation='nearest',
               norm=nm)
    cax.plot([arr.min(), arr.min()], [0, 1], 'k-')
    cax.plot([arr.max(), arr.max()], [0, 1], 'w-')
    cax.axis(cax_limits)
    cax.yaxis.set_visible(False)
    cax.xaxis.tick_bottom()
    cax.xaxis.set_major_locator(plt.LinearLocator(5))
    cax.set_xticklabels(cax.get_xticks(), size=5)
    #cax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
    return ax, cax
Exemplo n.º 13
0
def imageDescriptorTime(title=False, filename=None, show=False):
    smallX, smallY = splitIntoXY(data.DATA_300x300["descriptorImage"])
    mediumX, mediumY = splitIntoXY(data.DATA_640x480["descriptorImage"])
    largeX, largeY = splitIntoXY(data.DATA_1280x720["descriptorImage"])

    fig, (upper, bottom) = plt.subplots(2, 1, sharex=True, figsize=PICTURE_SIZE)

    if title:
        bottom.set_title("Délka výpočtu deskriptoru obrázku", fontsize="xx-large")

    setupXAxis(bottom)

    fig.text(0.04, 0.55, "Délka výpočtu deskriptoru obrázku [ms]", va="center", rotation="vertical", fontsize="xx-large")

    for axis in [bottom, upper]:
        for tick in axis.get_yticklabels():
            tick.set_fontsize("x-large")

    bottom.set_ylim(0, 90)
    upper.set_ylim(100, 475)
    upper.xaxis.tick_top()
    # up to 3 bars (sizes), 0.8 is default and leaves a little room between algorithms
    barWidth = 0.8 / 3
    hW = barWidth / 2

    bottom.yaxis.set_major_locator(plt.LinearLocator(7))
    upper.yaxis.set_major_locator(plt.LinearLocator(6))

    bottom.bar(smallX - 2 * hW, smallY, barWidth, color=pickColors(COLORS_300x300, smallX), edgecolor="black")
    drawAcross([bottom, upper], mediumX, mediumY, barWidth, color=pickColors(COLORS_640x480, mediumX), edgecolor="black")
    drawAcross([bottom, upper], largeX + 2 * hW, largeY, barWidth, color=pickColors(COLORS_1280x720, largeX), edgecolor="black")

    bottom.legend(loc="center left", bbox_to_anchor=(1.0125, 1.02), handles=GRAY_LEGEND, fontsize='large')
    bottom.grid(True, axis="y")
    upper.grid(True, axis="y")

    drawAxisSplitters(bottom, upper)

    top = TOP_MARGIN_TITLE if title else TOP_MARGIN_NO_TITLE
    plt.subplots_adjust(**transformMargins(top=top, pictureSize=PICTURE_SIZE, **DEFAULT_MARGINS), hspace=0.15)

    if filename:
        plt.savefig(os.path.abspath(f"{OUTPUT_DIR}/{filename}"))
    if show:
        plt.show()
Exemplo n.º 14
0
def _generate_bar_chart_with_line_twinx(df, title, xaxis_rotation,
                                        xaxis_df_name, xaxis_label,
                                        yaxis1_df_name, yaxis2_df_name,
                                        yaxis1_label, yaxis2_label):
    sns.set(style="whitegrid")
    fig, ax = plt.subplots(figsize=(19, 6))

    # define the number of ticks
    NUM_TICKS = 11

    ax.yaxis.set_major_locator(plt.LinearLocator(numticks=NUM_TICKS))

    ax.set_title(title)
    ax2 = ax.twinx()

    sns.barplot(ax=ax, x=xaxis_df_name, y=yaxis1_df_name, data=df)
    sns.scatterplot(ax=ax2, x=xaxis_df_name, y=yaxis2_df_name, data=df)

    ax.set_xticklabels(labels=df[xaxis_df_name], rotation=xaxis_rotation)
    ax.set(xlabel=xaxis_label, ylabel=yaxis1_label)
    vals = ax.get_yticks()
    ax.set_yticklabels(
        ['${:,.0f}'.format(x).replace('$-', '-$') for x in vals])

    ax2.set(ylabel=yaxis2_label)

    ax2.set_yticks(
        np.linspace(ax2.get_yticks()[0],
                    ax2.get_yticks()[-1], len(ax.get_yticks())))
    ax2.yaxis.set_major_locator(plt.LinearLocator(numticks=NUM_TICKS))

    i = 0
    for line in df.index.values.tolist():
        ax2.text(i + 0.1,
                 df[yaxis2_df_name][line],
                 df[yaxis2_df_name][line],
                 horizontalalignment='left',
                 size='medium',
                 color='black',
                 weight='bold')
        i = i + 1
    plt.show()
    def plot_points(self, A: np.ndarray, size=(10, 10), title: str = None):
        import matplotlib.pyplot as plt

        plot_main_title_font = {
            'family': 'sans serif',
            'color': 'black',
            'weight': 'bold',
            'size': 18
        }

        fig, ax = plt.subplots(figsize=size)

        # Set title.
        if title != None:
            ax.set_title(label=title,
                         loc='center',
                         fontdict=plot_main_title_font,
                         pad=20)

        # Axis ticks.
        ax.get_xaxis().set_ticks([0, A.shape[0]])
        ax.get_yaxis().set_ticks([np.min(A), np.max(A)])

        ax.get_xaxis().set_major_locator(plt.MultipleLocator(len(A)))
        ax.get_xaxis().set_minor_locator(
            plt.LinearLocator(numticks=len(A) // 500))

        ax.get_yaxis().set_major_locator(plt.MultipleLocator(np.max(A)))
        ax.get_yaxis().set_minor_locator(plt.LinearLocator(numticks=10))

        ax.grid(b=True, which='both', axis='both')

        ax.plot(A,
                color='grey',
                marker='.',
                markerfacecolor='orange',
                markersize=10,
                alpha=0.5)

        return ax
Exemplo n.º 16
0
def scatterplot_fpi_results(frame, atlas, task, suffix=''):
    frame = frame.sort_values(by='pi_avg',
                              axis=0,
                              ascending=True,
                              inplace=False)
    dpi = 100
    h = max(0.22 * len(frame.index), 14)
    # h = max(0.20 * np.unique(frame.))
    fig, ax = plt.subplots(figsize=(10, h), dpi=dpi)

    sns.scatterplot('pi_avg',
                    frame.index,
                    ax=ax,
                    data=frame,
                    size=frame.pi_freq,
                    size_norm=(5**2, 20**2),
                    label='pi_avg',
                    markers='o')
    sns.scatterplot('pi_high',
                    frame.index,
                    ax=ax,
                    data=frame,
                    label='pi_high',
                    markers='o')

    ax.legend(title='Legend',
              loc='lower right')  # , markerscale=0.8)#, fontsize='xx-large')

    ax.yaxis.set_major_locator(plt.LinearLocator())

    if task == gbl.clf:
        # ax.xaxis.set_major_locator(plt.MultipleLocator(base=0.05))
        ax.xaxis.set_major_locator(plt.MaxNLocator())
    elif task == gbl.reg:
        ax.xaxis.set_major_locator(plt.MaxNLocator())

    ax.autoscale(enable=True)
    ax.set_aspect('auto')

    plt.title('Feature Importance')  # , fontsize='large')
    plt.ylabel('feature')  # , fontsize='large')
    plt.xlabel('permutation importance')  # , fontsize='large')

    plt.yticks(frame.index,
               weight='bold')  # , rotation='vertical')#, fontsize='x-small')
    # plt.tick_params(axis='x', width=2.0, grid_alpha=0.7)
    plt.grid(True)

    plt.tight_layout()  # prevent clipping
    plt.savefig('{}_{}_fpi{}.png'.format(atlas, task, suffix))
Exemplo n.º 17
0
def plot_all_spectrum(data_dict):

    for key, value in data_dict.items():
        plt.figure()
        x = value['wavelength']
        y = value['intensity']
        spectrum = value['spectrum']

        x, y = cut_lower_bound(380, x, y)

        if spectrum == 'Transmission Spectrum':
            x, y = cut_lower_bound(420, x, y)

        else:

            h = (max(y)) * (0.6)
            peaks, props = find_peaks(y, height=h, width=10, prominence=1)
            x_peaks = []
            y_peaks = []
            for peak in peaks:
                x_peaks.append(round(x[peak]))
                y_peaks.append(round(y[peak]))
                string = '(' + str(x_peaks) + ' , ' + str(y_peaks) + ')'
                plt.text(x[peak] + 0.3, y[peak] + 0.3, string, fontsize=8)
            plt.plot(x_peaks, y_peaks, 'x')
            plt.legend(['peaks', 'signals'])

        plt.plot(x, y)
        #plt.semilogy(x,y)

        plt.xlabel('wavelength (nm)')
        plt.ylabel('intensity (counts)')
        ax = plt.gca()

        ax.xaxis.set_major_locator(ticker.AutoLocator())
        ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
        ax.xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))

        ax.yaxis.set_major_locator(plt.LinearLocator(4))
        #ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
        ax.yaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))

        if spectrum == 'Absorbance Spectrum':
            plt.legend(['peaks', 'signals'])
        fileName = './Result/' + key + '.png'
        plt.title(key)
        mp.savefig(fileName)
        value['peaks'] = [x_peaks, y_peaks]
    # print(x,y)
    return 0
Exemplo n.º 18
0
    def plot(self, name='testing'):
        '''

        Parameters
        ----------
        name : TYPE, optional
            DESCRIPTION. The default is 'testing'.

        Returns
        -------
        None.

        '''
        fraction = 0.5
        width = 510
        fig, ax = plt.subplots(figsize=set_size(width, fraction), sharex='all')
        plt.plot(self.y50, 'red')
        plt.plot(self.y_test, 'orange')
        ax.fill_between(range(0, len(self.y50)),
                        self.y10,
                        self.y90,
                        color='grey',
                        alpha=0.5)
        #ax.grid(True, zorder=5)
        plt.plot(self.y50, color='red', alpha=0.8, label='OFAT')
        plt.plot(self.y_test, color='olive', alpha=0.8, label='ground truth')
        ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2f'))
        ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.0f'))
        ax.xaxis.set_major_locator(plt.LinearLocator(6))
        ax.yaxis.set_major_locator(plt.LinearLocator(6))
        #plt.legend(loc='upper right', bbox_to_anchor=(1.0, 1.05), ncol=2)
        ax.set_xlabel('Time (weeks)')
        ax.set_ylabel('Average price')
        plt.tight_layout()
        plt.savefig('../../ofat/figures/' + name + '.pdf',
                    format='pdf',
                    bbox_inches='tight')
Exemplo n.º 19
0
def plot_HessD(fig, arr, subx1, suby2, subsize, extent, interpolation, title,
               xlabel, ylabel, col_bool):
    if col_bool:
        cm = matplotlib.cm.jet  #makecmap(arr)
        nm = cl.SymLogNorm(vmin=-0.1,
                           vmax=arr.max(),
                           linthresh=0.03,
                           linscale=0.03)
        cmap_ofs = 0.
    else:
        cm = makecmap(arr)
        nm = None
        cmap_ofs = 0.05
    #cm.set_gamma(0.2)
    ax = fig.add_axes([subx1, suby2, subsize, subsize])
    ax.imshow(arr,
              cmap=cm,
              aspect='auto',
              extent=extent,
              interpolation=interpolation,
              norm=nm)
    ax.set_title(title, fontsize=8)
    ax.set_xlabel(xlabel, fontsize=8)
    ax.set_ylabel(ylabel, fontsize=8)
    ax.set_xticklabels(ax.get_xticks(), size=8)
    ax.set_yticklabels(ax.get_yticks(), size=8)
    #cax = fig.add_axes([subx1+0.13, suby2+0.35, subsize-0.15, subsize-0.365])
    cax = fig.add_axes([
        subx1 + 0.07 + cmap_ofs, suby2 + 0.225, subsize - 0.10 - cmap_ofs,
        subsize - 0.235
    ])
    cb_arr = np.linspace(arr.min(), arr.max(), 1e2).reshape(1, 1e2)
    cax_limits = [np.floor(arr.min()), np.ceil(arr.max()), 0, 1]
    cax.imshow(cb_arr,
               cmap=cm,
               aspect='auto',
               extent=cax_limits,
               interpolation='nearest',
               norm=nm)
    cax.plot([arr.min(), arr.min()], [0, 1], 'k-')
    cax.plot([arr.max(), arr.max()], [0, 1], 'w-')
    cax.axis(cax_limits)
    cax.yaxis.set_visible(False)
    cax.xaxis.tick_bottom()
    cax.xaxis.set_major_locator(plt.LinearLocator(5))
    cax.set_xticklabels(cax.get_xticks(), size=5)
    #cax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
    return ax, cax
Exemplo n.º 20
0
def year_avg_timeseries(df, height=1.5, aspect=1, col_wrap=None):
    df2 = df.groupby(["site_no", df.lev_dt.dt.year]).lev_va.mean()
    df2 = df2.reset_index()
    g = sns.FacetGrid(df2,
                      col="site_no",
                      col_wrap=col_wrap,
                      height=height,
                      aspect=aspect,
                      sharex=False,
                      sharey=False)
    g = g.map(plt.plot, "lev_dt", "lev_va", marker=".")
    g.set_xticklabels(rotation=75)

    for ax in g.axes.flatten():
        ax.xaxis.set_major_locator(plt.LinearLocator(5))
    plt.show()
Exemplo n.º 21
0
def show_histogram_2d(x, y, z):
    fig = plt.figure(figsize=(10, 7))
    ax = fig.gca(projection='3d')
    X, Y = np.meshgrid(x, y)
    Z = z
    surf = ax.plot_surface(X,
                           Y,
                           Z,
                           rstride=1,
                           cstride=1,
                           cmap=plt.cm.coolwarm,
                           linewidth=0,
                           antialiased=False)
    ax.set_zlim(0, np.max(Z))
    #ax.set_zlim(0, 0.005)
    ax.zaxis.set_major_locator(plt.LinearLocator(10))
    ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.06f'))
    fig.colorbar(surf, shrink=0.5, aspect=7, cmap=plt.cm.coolwarm)
    plt.show()
Exemplo n.º 22
0
 def plot3d(self, fig, ax, points=100):
     x = np.linspace(self.Lower, self.Upper, points)
     y = np.linspace(self.Lower, self.Upper, points)
     X, Y = np.meshgrid(x, y)
     solution = [X, Y]
     Z = self.Fun(solution)
     surf = ax.plot_surface(X,
                            Y,
                            Z,
                            rstride=1,
                            cstride=1,
                            linewidth=0.1,
                            edgecolors='k',
                            alpha=0.5,
                            antialiased=True,
                            cmap=cm.RdPu_r,
                            zorder=1)
     ax.zaxis.set_major_locator(plt.LinearLocator(10))
     ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.01f'))
Exemplo n.º 23
0
def line_plot(results, figsize=None):
    df = pd.DataFrame(results.records, columns=results.columns)
    ax = df.plot(figsize=figsize, legend=False)
    ax.set_ylim(-100, 100)
    trend_name = results.metadata[1]['name']
    ax.fill_between(df["Datestamp"], df[trend_name].tolist(), color='#eeefff')

    ax.margins(0)
    ax.xaxis.set_major_locator(plt.LinearLocator(3))
    y_tick_labels = []
    for y in ax.get_yticks():
        if str(y) == "0.0":
            y_tick_labels.append("baseline")
        else:
            y_tick_labels.append(str(y)[:-2] + "%")
    ax.set_yticklabels(y_tick_labels)

    plt.close()
    return ax
def test_twin_axis_locaters_formatters():
    vals = np.linspace(0, 1, num=5, endpoint=True)
    locs = np.sin(np.pi * vals / 2.0)

    majl = plt.FixedLocator(locs)
    minl = plt.FixedLocator([0.1, 0.2, 0.3])

    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)
    ax1.plot([0.1, 100], [0, 1])
    ax1.yaxis.set_major_locator(majl)
    ax1.yaxis.set_minor_locator(minl)
    ax1.yaxis.set_major_formatter(plt.FormatStrFormatter('%08.2lf'))
    ax1.yaxis.set_minor_formatter(plt.FixedFormatter(['tricks', 'mind', 'jedi']))

    ax1.xaxis.set_major_locator(plt.LinearLocator())
    ax1.xaxis.set_minor_locator(plt.FixedLocator([15, 35, 55, 75]))
    ax1.xaxis.set_major_formatter(plt.FormatStrFormatter('%05.2lf'))
    ax1.xaxis.set_minor_formatter(plt.FixedFormatter(['c', '3', 'p', 'o']))
    ax2 = ax1.twiny()
    ax3 = ax1.twinx()
Exemplo n.º 25
0
def buildPlot(gMat):
    fig = plt.figure(figsize=(16, 4))
    ax1 = fig.add_subplot(121, projection='3d')
    ax2 = fig.add_subplot(122)
    X = np.arange(0, YDIM)
    Y = np.arange(0, XDIM)
    X, Y = np.meshgrid(X, Y)
    surf = ax1.plot_surface(X,
                            Y,
                            gMat,
                            rstride=1,
                            cstride=1,
                            cmap=plt.cm.coolwarm,
                            linewidth=0,
                            antialiased=False)
    ax1.set_zlim(-0.5, 1.5)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    ax1.zaxis.set_major_locator(plt.LinearLocator(10))
    ax1.zaxis.set_major_formatter(plt.FormatStrFormatter('%.02f'))

    imgObj = ax2.imshow(gMat, vmin=0.0, vmax=1.0)
    return fig, ax1, ax2, X, Y, surf, imgObj
Exemplo n.º 26
0
    def setup(self, axes, x):
        self.axes = axes
        self.net.setup()
        self.keys = self.keys or self.net.keys
        self.labels = []
        for key in self.keys:
            self.labels += [f'{key} RX', f'{key} TX']
        self.ys = [common.none_array(x.size) for _ in self.labels]
        self.lines = [
            axes.plot(x, y, label=label)[0]
            for label, y in zip(self.labels, self.ys)
        ]

        axes.set_title('Network')
        axes.set_ylabel('Network IO')
        axes.set_xlim(x.min(), x.max())
        axes.set_ylim(0, self.ylim)
        axes.tick_params('x', bottom=False, labelbottom=False)
        axes.grid(True, axis='y')
        axes.legend()
        axes.yaxis.set_major_locator(plt.LinearLocator(5))
        axes.yaxis.set_major_formatter(plt.FuncFormatter(self._format_ylabel))

        return self.lines
Exemplo n.º 27
0
def plot_x_y(x_values, y_values, x_name, y_name, graph_name, line_type,
             **kwargs):
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))

    # plt.suptitle(graph_name, y=1.0, fontsize=17)
    #
    # plt.xlabel(x_name, fontsize=16)
    # plt.ylabel(y_name, fontsize=16)

    plt.suptitle(graph_name)

    plt.xlabel(x_name)
    plt.ylabel(y_name)

    # plt.xlim(min(x_values) - 0.1 * min(x_values),
    #          max(x_values) + 0.1 * max(x_values))
    # plt.ylim(min(y_values), max(y_values) + 0.1 * max(y_values))

    # plt.ylim(min(y_values), max(y_values) + 0.05 * max(y_values))

    plt.ticklabel_format(axis="x", style="plain")
    ax = plt.gca()
    plt.plot(x_values, y_values, line_type, **kwargs)
    ax.yaxis.set_major_locator(plt.LinearLocator(numticks=6))
Exemplo n.º 28
0
sns.set(style="white", palette="Set2")

# plot Adjusted R2 against mu and d
fig = plt.figure(figsize=(10, 7))
ax = fig.gca(projection='3d')
x = np.arange(-5., 5., 0.3)
y = np.arange(-5., 5., 0.3)
X, Y = np.meshgrid(x, y)
Z = np.maximum(X, Y)

surf = ax.plot_wireframe(X,
                         Y,
                         Z,
                         rstride=1,
                         cstride=1,
                         cmap=plt.cm.coolwarm,
                         linewidth=0.5,
                         antialiased=True)

ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('MaxPool(X1, X2)')
ax.zaxis.set_major_locator(plt.LinearLocator(10))
ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.02f'))
ax.vieW_init(30, -100)

# fig.colorbar(surf, shrink=0.5, aspect=7, cmap=plt.cm.coolwarm)
# matplotlib.rcParams['lines.linewidth'] = 2
plt.tight_layout()
# plt.show()
plt.savefig("./maxpool.pdf")
    df['hm'] = df['heure minutes'].apply(lambda x: int(100 * int(
        x.split(':')[0]) + (5 / 3) * int(x.split(':')[1])))

    #save file for use in ML algorithm UNCOMMENT BELOW IF NEVER RUN BEFORE
    # df.to_csv(r'begles_3month_Data.csv',sep = ';')

    #%% plots

    #start with 4*4 grid for initial view
    fig_sig, ax_sig = plt.subplots(2, 2, figsize=(18, 10))
    plt.suptitle('Données 01/09 - 20/12 2018')

    ax_sig[0, 0].plot(df_original)
    ax_sig[0, 0].set_title('Courbe de Charge')
    ax_sig[0, 0].set_ylabel('P / kW', rotation=90)
    ax_sig[0, 0].xaxis.set_major_locator(plt.LinearLocator(4))

    ax_sig[0, 1].plot(df.groupby('heure minutes').mean()['PS ATTEINTE'])
    ax_sig[0, 1].set_title('PS ATTEINTE Moyenne Journalière')
    ax_sig[0, 1].set_ylabel('P / kW', rotation=90)
    ax_sig[0, 1].xaxis.set_major_locator(plt.LinearLocator(9))

    ax_sig[1, 0].plot(df.groupby('weekday').mean()['PS ATTEINTE'])
    ax_sig[1, 0].set_title('PS ATTEINTE Moyenne Semaine')
    ax_sig[1, 0].set_ylabel('P / kW', rotation=90)
    ax_sig[1, 0].set_xlabel('Jour de la Semaine')

    ax_sig[1, 1].scatter(df['Temperature'], df['PS ATTEINTE'])
    ax_sig[1, 1].set_title('Distribution PS ATTEINTE - Temperature')
    ax_sig[1, 1].set_ylabel('P / kW', rotation=90)
Exemplo n.º 30
0
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))

# Explained variance score: 1 is perfect prediction
print("Variance score: %.2f" % r2_score(y_test, y_pred))
"""
  plot actual high and predict high from 2018-02-01 to 2018-02-28
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

fig, ax = plt.subplots()

predictions = reg.predict(scaler.transform(data[:cut_point]))

ax.plot(dates[:cut_point].astype('O'), data[:cut_point, 1], 'b-',
        dates[:cut_point].astype('O'), predictions, 'r-')

blue_patch = mpatches.Patch(color='blue', label='actual')
red_patch = mpatches.Patch(color='red', label='predict')
plt.legend(handles=[blue_patch, red_patch])

# format tricker
import matplotlib.dates as mdates

ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

ax.yaxis.set_major_locator(plt.LinearLocator())

plt.show()