Python matplotlib.pyplot.setp() Examples

The following are 30 code examples of matplotlib.pyplot.setp(). 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.pyplot , or try the search function .
Example #1
Source File: plot.py    From TaskBot with GNU General Public License v3.0 6 votes vote down vote up
def plot_attention(sentences, attentions, labels, **kwargs):
    fig, ax = plt.subplots(**kwargs)
    im = ax.imshow(attentions, interpolation='nearest',
                   vmin=attentions.min(), vmax=attentions.max())
    plt.colorbar(im, shrink=0.5, ticks=[0, 1])
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")
    ax.set_yticks(range(len(labels)))
    ax.set_yticklabels(labels, fontproperties=getChineseFont())
    # Loop over data dimensions and create text annotations.
    for i in range(attentions.shape[0]):
        for j in range(attentions.shape[1]):
            text = ax.text(j, i, sentences[i][j],
                           ha="center", va="center", color="b", size=10,
                           fontproperties=getChineseFont())

    ax.set_title("Attention Visual")
    fig.tight_layout()
    plt.show() 
Example #2
Source File: DyStockDataViewer.py    From DevilYuan with MIT License 6 votes vote down vote up
def plotTimeShareChart(self, code, date, n):

        date = self._daysEngine.codeTDayOffset(code, date, n)
        if date is None: return

        DyMatplotlib.newFig()

        # plot stock time share chart
        self._plotTimeShareChart(code, date, left=0.05, right=0.95, top=0.95, bottom=0.05)

        # plot index time share chart
        #self._plotTimeShareChart(self._daysEngine.getIndex(code), date, left=0.05, right=0.95, top=0.45, bottom=0.05)

        # layout
        f = plt.gcf()
        plt.setp([a.get_xticklabels() for a in f.axes[::2]], visible=False)
        f.show() 
Example #3
Source File: visualize_attention.py    From atis with MIT License 6 votes vote down vote up
def render(self, filename):
        """
        Renders the attention graph over timesteps.

        Args:
          filename (string): filename to save the figure to.
        """
        figure, axes = plt.subplots()
        graph = np.stack(self.attentions)

        axes.imshow(graph, cmap=plt.cm.Blues, interpolation="nearest")
        axes.xaxis.tick_top()
        axes.set_xticks(range(len(self.keys)))
        axes.set_xticklabels(self.keys)
        plt.setp(axes.get_xticklabels(), rotation=90)
        axes.set_yticks(range(len(self.generated_values)))
        axes.set_yticklabels(self.generated_values)
        axes.set_aspect(1, adjustable='box')
        plt.tick_params(axis='x', which='both', bottom='off', top='off')
        plt.tick_params(axis='y', which='both', left='off', right='off')

        figure.savefig(filename) 
Example #4
Source File: test_artist.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_setp():
    # Check empty list
    plt.setp([])
    plt.setp([[]])

    # Check arbitrary iterables
    fig, axes = plt.subplots()
    lines1 = axes.plot(range(3))
    lines2 = axes.plot(range(3))
    martist.setp(chain(lines1, lines2), 'lw', 5)
    plt.setp(axes.spines.values(), color='green')

    # Check `file` argument
    sio = io.StringIO()
    plt.setp(lines1, 'zorder', file=sio)
    assert sio.getvalue() == '  zorder: float\n' 
Example #5
Source File: plotting.py    From Computable with MIT License 6 votes vote down vote up
def _label_axis(ax, kind='x', label='', position='top',
    ticks=True, rotate=False):

    from matplotlib.artist import setp
    if kind == 'x':
        ax.set_xlabel(label, visible=True)
        ax.xaxis.set_visible(True)
        ax.xaxis.set_ticks_position(position)
        ax.xaxis.set_label_position(position)
        if rotate:
            setp(ax.get_xticklabels(), rotation=90)
    elif kind == 'y':
        ax.yaxis.set_visible(True)
        ax.set_ylabel(label, visible=True)
        # ax.set_ylabel(a)
        ax.yaxis.set_ticks_position(position)
        ax.yaxis.set_label_position(position)
    return 
Example #6
Source File: visFunction.py    From uiKLine with MIT License 6 votes vote down vote up
def plotSigHeats(signals,markets,start=0,step=2,size=1,iters=6):
    """
    打印信号回测盈损热度图,寻找参数稳定岛
    """
    sigMat = pd.DataFrame(index=range(iters),columns=range(iters))
    for i in range(iters):
        for j in range(iters):
            climit = start + i*step
            wlimit = start + j*step
            caps,poss = plotSigCaps(signals,markets,climit=climit,wlimit=wlimit,size=size,op=False)
            sigMat[i][j] = caps[-1]
    sns.heatmap(sigMat.values.astype(np.float64),annot=True,fmt='.2f',annot_kws={"weight": "bold"})
    xTicks   = [i+0.5 for i in range(iters)]
    yTicks   = [iters-i-0.5 for i in range(iters)]
    xyLabels = [str(start+i*step) for i in range(iters)]
    _, labels = plt.yticks(yTicks,xyLabels)
    plt.setp(labels, rotation=0)
    _, labels = plt.xticks(xTicks,xyLabels)
    plt.setp(labels, rotation=90)
    plt.xlabel('Loss Stop @')
    plt.ylabel('Profit Stop @')
    return sigMat 
Example #7
Source File: AE_ts_model.py    From AE_ts with MIT License 6 votes vote down vote up
def plot_data(X_train, y_train, plot_row=5):
    counts = dict(Counter(y_train))
    num_classes = len(np.unique(y_train))
    f, axarr = plt.subplots(plot_row, num_classes)
    for c in np.unique(y_train):  # Loops over classes, plot as columns
        c = int(c)
        ind = np.where(y_train == c)
        ind_plot = np.random.choice(ind[0], size=plot_row)
        for n in range(plot_row):  # Loops over rows
            axarr[n, c].plot(X_train[ind_plot[n], :])
            # Only shops axes for bottom row and left column
            if n == 0:
                axarr[n, c].set_title('Class %.0f (%.0f)' % (c, counts[float(c)]))
            if not n == plot_row - 1:
                plt.setp([axarr[n, c].get_xticklabels()], visible=False)
            if not c == 0:
                plt.setp([axarr[n, c].get_yticklabels()], visible=False)
    f.subplots_adjust(hspace=0)  # No horizontal space between subplots
    f.subplots_adjust(wspace=0)  # No vertical space between subplots
    plt.show()
    return 
Example #8
Source File: DyStockDataViewer.py    From DevilYuan with MIT License 6 votes vote down vote up
def _plotAckRWExtremas(self, event):
        code = event.data['code']
        df = event.data['df']
        regionalLocals = event.data['regionalLocals']

        DyMatplotlib.newFig()
        f = plt.gcf()

        index = df.index
        startDay = index[0].strftime('%Y-%m-%d')
        endDay = index[-1].strftime('%Y-%m-%d')

        # plot stock
        periods = self._plotCandleStick(code, startDate=startDay, endDate=endDay, baseDate=endDay, left=0.05, right=0.95, top=0.95, bottom=0.5, maIndicator='close')

        self._plotRegionalLocals(f.axes[0], index, regionalLocals)

        plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
        f.show() 
Example #9
Source File: DyStockDataViewer.py    From DevilYuan with MIT License 6 votes vote down vote up
def _plotAckHSARs(self, event):
        code = event.data['code']
        df = event.data['df']
        hsars = event.data['hsars']

        DyMatplotlib.newFig()
        f = plt.gcf()

        index = df.index
        startDay = index[0].strftime('%Y-%m-%d')
        endDay = index[-1].strftime('%Y-%m-%d')

        # plot stock
        periods = self._plotCandleStick(code, startDate=startDay, endDate=endDay, baseDate=endDay, left=0.05, right=0.95, top=0.95, bottom=0.5, maIndicator='close')

        self._plotHSARs(f.axes[0], hsars)

        plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
        f.show() 
Example #10
Source File: chord_plot.py    From jMetalPy with MIT License 6 votes vote down vote up
def hover_over_bin(event, handle_tickers, handle_plots, colors, fig):
    is_found = False

    for iobj in range(len(handle_tickers)):
        for ibin in range(len(handle_tickers[iobj])):
            cont = False
            if not is_found:
                cont, ind = handle_tickers[iobj][ibin].contains(event)
                if cont:
                    is_found = True
            if cont:
                plt.setp(handle_tickers[iobj][ibin], facecolor=colors[iobj])
                [h.set_visible(True) for h in handle_plots[iobj][ibin]]
                is_found = True
                fig.canvas.draw_idle()
            else:
                plt.setp(handle_tickers[iobj][ibin], facecolor=(1, 1, 1))
                for h in handle_plots[iobj][ibin]:
                    h.set_visible(False)
                fig.canvas.draw_idle() 
Example #11
Source File: DyStockDataViewer.py    From DevilYuan with MIT License 6 votes vote down vote up
def plotAckKama(self, event):
        code, startDate, endDate = '002551.SZ', '2015-07-01', '2016-03-01'

        # load
        if not self._daysEngine.load([-200, startDate, endDate], codes=[code]):
            return

        DyMatplotlib.newFig()

        # plot basic stock K-Chart
        periods = self._plotCandleStick(code, startDate=startDate, endDate=endDate, netCapitalFlow=True, left=0.05, right=0.95, top=0.95, bottom=0.5)
        
        # plot customized stock K-Chart
        self._plotKamaCandleStick(code, periods=periods, left=0.05, right=0.95, top=0.45, bottom=0.05)

        # layout
        f = plt.gcf()
        plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
        f.show() 
Example #12
Source File: SpectraKeras_MLP.py    From SpectralMachine with GNU General Public License v3.0 6 votes vote down vote up
def plotWeights(En, A, model):
    import matplotlib.pyplot as plt
    plt.figure(tight_layout=True)
    plotInd = 511
    for layer in model.layers:
        try:
            w_layer = layer.get_weights()[0]
            ax = plt.subplot(plotInd)
            newX = np.arange(En[0], En[-1], (En[-1]-En[0])/w_layer.shape[0])
            plt.plot(En, np.interp(En, newX, w_layer[:,0]), label=layer.get_config()['name'])
            plt.legend(loc='upper right')
            plt.setp(ax.get_xticklabels(), visible=False)
            plotInd +=1
        except:
            pass

    ax1 = plt.subplot(plotInd)
    ax1.plot(En, A[0], label='Sample data')

    plt.xlabel('Raman shift [1/cm]')
    plt.legend(loc='upper right')
    plt.savefig('keras_MLP_weights' + '.png', dpi = 160, format = 'png')  # Save plot

#************************************ 
Example #13
Source File: viz.py    From dgl with Apache License 2.0 6 votes vote down vote up
def draw_heatmap(array, input_seq, output_seq, dirname, name):
    dirname = os.path.join('log', dirname)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    fig, axes = plt.subplots(2, 4)
    cnt = 0
    for i in range(2):
        for j in range(4):
            axes[i, j].imshow(array[cnt].transpose(-1, -2))
            axes[i, j].set_yticks(np.arange(len(input_seq)))
            axes[i, j].set_xticks(np.arange(len(output_seq)))
            axes[i, j].set_yticklabels(input_seq, fontsize=4)
            axes[i, j].set_xticklabels(output_seq, fontsize=4)
            axes[i, j].set_title('head_{}'.format(cnt), fontsize=10)
            plt.setp(axes[i, j].get_xticklabels(), rotation=45, ha="right",
                     rotation_mode="anchor")
            cnt += 1

    fig.suptitle(name, fontsize=12)
    plt.tight_layout()
    plt.savefig(os.path.join(dirname, '{}.pdf'.format(name)))
    plt.close() 
Example #14
Source File: SpectraKeras_CNN.py    From SpectralMachine with GNU General Public License v3.0 6 votes vote down vote up
def plotWeights(En, A, model):
    import matplotlib.pyplot as plt
    plt.figure(tight_layout=True)
    plotInd = 511
    for layer in model.layers:
        try:
            w_layer = layer.get_weights()[0]
            ax = plt.subplot(plotInd)
            newX = np.arange(En[0], En[-1], (En[-1]-En[0])/w_layer.shape[0])
            plt.plot(En, np.interp(En, newX, w_layer[:,0]), label=layer.get_config()['name'])
            plt.legend(loc='upper right')
            plt.setp(ax.get_xticklabels(), visible=False)
            plotInd +=1
        except:
            pass

    ax1 = plt.subplot(plotInd)
    ax1.plot(En, A[0], label='Sample data')

    plt.xlabel('Raman shift [1/cm]')
    plt.legend(loc='upper right')
    plt.savefig('keras_MLP_weights' + '.png', dpi = 160, format = 'png')  # Save plot

#************************************ 
Example #15
Source File: PiecewiseConstant.py    From python_primer with MIT License 6 votes vote down vote up
def _test():
    PC = PiecewiseConstant([(0.4, 1), (0.2, 1.5), (0.1, 3)], xmax=4)
    I, I_s = Indicator(-3, 5), Indicator(-3, 5, eps=1)
    H, H_s = Heaviside(), Heaviside(eps=1)
    ax1 = plt.subplot(311)
    ax2, ax3 = plt.subplot(323),  plt.subplot(324)
    ax4, ax5 = plt.subplot(325),  plt.subplot(326)

    x, y = PC.plot()
    ax1.plot(x, y)
    ax1.set_ylim([0, 0.5])
    ax1.set_title('PiecewiseConstant')
    titles = ['Indicator', 'Indicator (eps=1)',
              'Heaviside', 'Heaviside (eps=1)']
    for f, ax, title in zip([I, I_s, H, H_s], [ax2, ax3, ax4, ax5], titles):
        x, y = f.plot(-6, 8)
        ax.plot(x, y)
        ax.set_ylim([-0.5, 1.5])
        ax.set_title(title)
    for ax in [ax2, ax3]:
        plt.setp(ax.get_xticklabels(), visible=False)
    plt.show() 
Example #16
Source File: visFunction.py    From uiKLine with MIT License 6 votes vote down vote up
def plotSigHeats(signals,markets,start=0,step=2,size=1,iters=6):
    """
    打印信号回测盈损热度图,寻找参数稳定岛
    """
    sigMat = pd.DataFrame(index=range(iters),columns=range(iters))
    for i in range(iters):
        for j in range(iters):
            climit = start + i*step
            wlimit = start + j*step
            caps,poss = plotSigCaps(signals,markets,climit=climit,wlimit=wlimit,size=size,op=False)
            sigMat[i][j] = caps[-1]
    sns.heatmap(sigMat.values.astype(np.float64),annot=True,fmt='.2f',annot_kws={"weight": "bold"})
    xTicks   = [i+0.5 for i in range(iters)]
    yTicks   = [iters-i-0.5 for i in range(iters)]
    xyLabels = [str(start+i*step) for i in range(iters)]
    _, labels = plt.yticks(yTicks,xyLabels)
    plt.setp(labels, rotation=0)
    _, labels = plt.xticks(xTicks,xyLabels)
    plt.setp(labels, rotation=90)
    plt.xlabel('Loss Stop @')
    plt.ylabel('Profit Stop @')
    return sigMat 
Example #17
Source File: utils.py    From seq2seq-summarizer with MIT License 6 votes vote down vote up
def show_attention_map(src_words, pred_words, attention, pointer_ratio=None):
  fig, ax = plt.subplots(figsize=(16, 4))
  im = plt.pcolormesh(np.flipud(attention), cmap="GnBu")
  # set ticks and labels
  ax.set_xticks(np.arange(len(src_words)) + 0.5)
  ax.set_xticklabels(src_words, fontsize=14)
  ax.set_yticks(np.arange(len(pred_words)) + 0.5)
  ax.set_yticklabels(reversed(pred_words), fontsize=14)
  if pointer_ratio is not None:
    ax1 = ax.twinx()
    ax1.set_yticks(np.concatenate([np.arange(0.5, len(pred_words)), [len(pred_words)]]))
    ax1.set_yticklabels('%.3f' % v for v in np.flipud(pointer_ratio))
    ax1.set_ylabel('Copy probability', rotation=-90, va="bottom")
  # let the horizontal axes labelling appear on top
  ax.tick_params(top=True, bottom=False, labeltop=True, labelbottom=False)
  # rotate the tick labels and set their alignment
  plt.setp(ax.get_xticklabels(), rotation=-45, ha="right", rotation_mode="anchor") 
Example #18
Source File: burst_plot.py    From FRETBursts with GNU General Public License v2.0 6 votes vote down vote up
def _alex_plot_style(g, colorbar=True):
    """Set plot style and colorbar for an ALEX joint plot.
    """
    g.set_axis_labels(xlabel="E", ylabel="S")
    g.ax_marg_x.grid(True)
    g.ax_marg_y.grid(True)
    g.ax_marg_x.set_xlabel('')
    g.ax_marg_y.set_ylabel('')
    plt.setp(g.ax_marg_y.get_xticklabels(), visible=True)
    plt.setp(g.ax_marg_x.get_yticklabels(), visible=True)
    g.ax_marg_x.locator_params(axis='y', tight=True, nbins=3)
    g.ax_marg_y.locator_params(axis='x', tight=True, nbins=3)
    if colorbar:
        pos = g.ax_joint.get_position().get_points()
        X, Y = pos[:, 0], pos[:, 1]
        cax = plt.axes([1., Y[0], (X[1] - X[0]) * 0.045, Y[1] - Y[0]])
        plt.colorbar(cax=cax) 
Example #19
Source File: matplotlib_trading_chart.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def render(self, current_step, net_worths, benchmarks, trades, window_size=50):
        net_worth = round(net_worths[-1], 2)
        initial_net_worth = round(net_worths[0], 2)
        profit_percent = round((net_worth - initial_net_worth) / initial_net_worth * 100, 2)

        self.fig.suptitle('Net worth: $' + str(net_worth) +
                          ' | Profit: ' + str(profit_percent) + '%')

        window_start = max(current_step - window_size, 0)
        step_range = slice(window_start, current_step)
        times = self.df.index.values[step_range]

        self._render_net_worth(step_range, times, current_step, net_worths, benchmarks)
        self._render_price(step_range, times, current_step)
        self._render_volume(step_range, times)
        self._render_trades(step_range, trades)

        self.price_ax.set_xticklabels(times, rotation=45, horizontalalignment='right')

        # Hide duplicate net worth date labels
        plt.setp(self.net_worth_ax.get_xticklabels(), visible=False)

        # Necessary to view frames before they are unrendered
        plt.pause(0.001) 
Example #20
Source File: plot_helpers.py    From topmodel with MIT License 5 votes vote down vote up
def plot_boxplot(vals, label):
    fig, ax = plt.subplots()
    ax.boxplot(vals)
    plt.setp(ax, xticklabels=label)
    return save_image() 
Example #21
Source File: plotter.py    From message-analyser with MIT License 5 votes vote down vote up
def pie_messages_per_author(msgs, your_name, target_name, path_to_save):
    forwarded = len([msg for msg in msgs if msg.is_forwarded])
    msgs = list(filter(lambda msg: not msg.is_forwarded, msgs))
    your_messages_len = len([msg for msg in msgs if msg.author == your_name])
    target_messages_len = len(msgs) - your_messages_len
    data = [your_messages_len, target_messages_len, forwarded]
    labels = [f"{your_name}\n({your_messages_len})",
              f"{target_name}\n({target_messages_len})",
              f"forwarded\n({forwarded})"]
    explode = (.0, .0, .2)

    fig, ax = plt.subplots(figsize=(13, 8), subplot_kw=dict(aspect="equal"))

    wedges, _, autotexts = ax.pie(x=data, explode=explode, colors=["#4982BB", "#5C6093", "#53B8D7"],
                                  autopct=lambda pct: f"{pct:.1f}%",
                                  wedgeprops={"edgecolor": "black", "alpha": 0.8})

    ax.legend(wedges, labels,
              loc="upper right",
              bbox_to_anchor=(1, 0, 0.5, 1))

    plt.setp(autotexts, size=10, weight="bold")

    fig.savefig(os.path.join(path_to_save, pie_messages_per_author.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{pie_messages_per_author.__name__} was created.") 
Example #22
Source File: PlotROC.py    From 3D-convolutional-speaker-recognition with Apache License 2.0 5 votes vote down vote up
def Plot_ROC_Fn(label,distance,save_path):

    fpr, tpr, thresholds = metrics.roc_curve(label, distance, pos_label=1)
    AUC = metrics.roc_auc_score(label, distance, average='macro', sample_weight=None)
    # AP = metrics.average_precision_score(label, -distance, average='macro', sample_weight=None)

    # Calculating EER
    intersect_x = fpr[np.abs(fpr - (1 - tpr)).argmin(0)]
    EER = intersect_x
    print("EER = ", float(("{0:.%ie}" % 1).format(intersect_x)))

    # AUC(area under the curve) calculation
    print("AUC = ", float(("{0:.%ie}" % 1).format(AUC)))

    # # AP(average precision) calculation.
    # # This score corresponds to the area under the precision-recall curve.
    # print("AP = ", float(("{0:.%ie}" % 1).format(AP)))

    # Plot the ROC
    fig = plt.figure()
    ax = fig.gca()
    lines = plt.plot(fpr, tpr, label='ROC Curve')
    plt.setp(lines, linewidth=2, color='r')
    ax.set_xticks(np.arange(0, 1.1, 0.1))
    ax.set_yticks(np.arange(0, 1.1, 0.1))
    plt.title('ROC.jpg')
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')

    # # Cutting the floating number
    # AUC = '%.2f' % AUC
    # EER = '%.2f' % EER
    # # AP = '%.2f' % AP
    #
    # # Setting text to plot
    # # plt.text(0.5, 0.6, 'AP = ' + str(AP), fontdict=None)
    # plt.text(0.5, 0.5, 'AUC = ' + str(AUC), fontdict=None)
    # plt.text(0.5, 0.4, 'EER = ' + str(EER), fontdict=None)
    plt.grid()
    plt.show()
    fig.savefig(save_path) 
Example #23
Source File: regression03.py    From AILearners with Apache License 2.0 5 votes vote down vote up
def plotstageWiseMat():
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
    xArr, yArr = loadDataSet('C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/abalone.txt')
    returnMat = stageWise(xArr, yArr, 0.005, 1000)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(returnMat)    
    ax_title_text = ax.set_title(u'前向逐步回归:迭代次数与回归系数的关系', FontProperties = font)
    ax_xlabel_text = ax.set_xlabel(u'迭代次数', FontProperties = font)
    ax_ylabel_text = ax.set_ylabel(u'回归系数', FontProperties = font)
    plt.setp(ax_title_text, size = 15, weight = 'bold', color = 'red')
    plt.setp(ax_xlabel_text, size = 10, weight = 'bold', color = 'black')
    plt.setp(ax_ylabel_text, size = 10, weight = 'bold', color = 'black')
    plt.show() 
Example #24
Source File: demo_axes_divider.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def demo_locatable_axes_hard(fig1):

    from mpl_toolkits.axes_grid1 import SubplotDivider, Size
    from mpl_toolkits.axes_grid1.mpl_axes import Axes

    divider = SubplotDivider(fig1, 2, 2, 2, aspect=True)

    # axes for image
    ax = Axes(fig1, divider.get_position())

    # axes for colorbar
    ax_cb = Axes(fig1, divider.get_position())

    h = [Size.AxesX(ax),  # main axes
         Size.Fixed(0.05),  # padding, 0.1 inch
         Size.Fixed(0.2),  # colorbar, 0.3 inch
         ]

    v = [Size.AxesY(ax)]

    divider.set_horizontal(h)
    divider.set_vertical(v)

    ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
    ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0))

    fig1.add_axes(ax)
    fig1.add_axes(ax_cb)

    ax_cb.axis["left"].toggle(all=False)
    ax_cb.axis["right"].toggle(ticks=True)

    Z, extent = get_demo_image()

    im = ax.imshow(Z, extent=extent, interpolation="nearest")
    plt.colorbar(im, cax=ax_cb)
    plt.setp(ax_cb.get_yticklabels(), visible=False) 
Example #25
Source File: analyse_results_paper.py    From YAFS with MIT License 5 votes vote down vote up
def set_box_color(bp, color):
    plt.setp(bp['boxes'], color=color)
    plt.setp(bp['whiskers'], color=color)
    plt.setp(bp['caps'], color=color)
    plt.setp(bp['medians'], color=color)
    
# =============================================================================
# Boxplot matriz of each app - gtw/user
# ============================================================================= 
Example #26
Source File: regression.py    From AILearners with Apache License 2.0 5 votes vote down vote up
def plotlwlrRegression():
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
    xArr, yArr = loadDataSet('C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/ex0.txt')                                    #加载数据集
    yHat_1 = lwlrTest(xArr, xArr, yArr, 1.0)                            #根据局部加权线性回归计算yHat
    yHat_2 = lwlrTest(xArr, xArr, yArr, 0.01)                            #根据局部加权线性回归计算yHat
    yHat_3 = lwlrTest(xArr, xArr, yArr, 0.003)                            #根据局部加权线性回归计算yHat
    xMat = np.mat(xArr)                                                    #创建xMat矩阵
    yMat = np.mat(yArr)                                                    #创建yMat矩阵
    srtInd = xMat[:, 1].argsort(0)                                        #排序,返回索引值
    xSort = xMat[srtInd][:,0,:]
    fig, axs = plt.subplots(nrows=3, ncols=1,sharex=False, sharey=False, figsize=(10,8))                                        
    axs[0].plot(xSort[:, 1], yHat_1[srtInd], c = 'red')                        #绘制回归曲线
    axs[1].plot(xSort[:, 1], yHat_2[srtInd], c = 'red')                        #绘制回归曲线
    axs[2].plot(xSort[:, 1], yHat_3[srtInd], c = 'red')                        #绘制回归曲线
    axs[0].scatter(xMat[:,1].flatten().A[0], yMat.flatten().A[0], s = 20, c = 'blue', alpha = .5)                #绘制样本点
    axs[1].scatter(xMat[:,1].flatten().A[0], yMat.flatten().A[0], s = 20, c = 'blue', alpha = .5)                #绘制样本点
    axs[2].scatter(xMat[:,1].flatten().A[0], yMat.flatten().A[0], s = 20, c = 'blue', alpha = .5)                #绘制样本点
    #设置标题,x轴label,y轴label
    axs0_title_text = axs[0].set_title(u'局部加权回归曲线,k=1.0',FontProperties=font)
    axs1_title_text = axs[1].set_title(u'局部加权回归曲线,k=0.01',FontProperties=font)
    axs2_title_text = axs[2].set_title(u'局部加权回归曲线,k=0.003',FontProperties=font)
    plt.setp(axs0_title_text, size=8, weight='bold', color='red')  
    plt.setp(axs1_title_text, size=8, weight='bold', color='red')  
    plt.setp(axs2_title_text, size=8, weight='bold', color='red')  
    plt.xlabel('X')
    plt.show() 
Example #27
Source File: demo_axes_divider.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def demo_simple_image(ax):
    Z, extent = get_demo_image()

    im = ax.imshow(Z, extent=extent, interpolation="nearest")
    cb = plt.colorbar(im)
    plt.setp(cb.ax.get_yticklabels(), visible=False) 
Example #28
Source File: plot_confusion_matrix.py    From quantum-neural-networks with Apache License 2.0 5 votes vote down vote up
def plot_confusion_matrix(cm, classes, title=None, cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """

    fig, ax = plt.subplots()
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)

    # We want to show all ticks...
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           # ... and label them with the respective list entries
           xticklabels=classes, yticklabels=classes,
           ylabel='True label',
           xlabel='Predicted label')

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    fmt = '.2f'
    thresh = cm.max() / 2.
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], fmt),
                    ha="center", va="center",
                    color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    return ax 
Example #29
Source File: confidence_analyzer.py    From assistant-dialog-skill-analysis with Apache License 2.0 5 votes vote down vote up
def create_threshold_graph(data):
    """
    display threshold analysis graph
    :param data:
    :return: None
    """
    sns.set(rc={"figure.figsize": (20.7, 10.27)})
    plt.ylim(0, 1.1)
    plt.axvline(0.2, 0, 1)
    plot = sns.lineplot(data=data, palette="tab10", linewidth=3.5)
    plt.setp(plot.legend().get_texts(), fontsize="22")
    plot.set_xlabel("Threshold T", fontsize=18)
    plot.set_ylabel("Metrics mentioned above", fontsize=18) 
Example #30
Source File: test_patheffects.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_patheffect2():

    ax2 = plt.subplot(111)
    arr = np.arange(25).reshape((5, 5))
    ax2.imshow(arr)
    cntr = ax2.contour(arr, colors="k")

    plt.setp(cntr.collections,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")])

    clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
    plt.setp(clbls,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")])