How to use the matplotlib.pyplot.legend function in matplotlib

To help you get started, we’ve selected a few matplotlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github muneebalam / scrapenhl2 / scrapenhl2 / plot / game_timeline.py View on Github external
if pd.isnull(cf_at_time_max):
                    cf_at_time_max = cf[team][cf[team].Time == end].CumCF.max()
                if i == 0:
                    ax2.axvspan(start, end, ymin=cf_at_time_min / ymax,
                                ymax=cf_at_time_max / ymax, alpha=0.5, facecolor=colors_to_use[team],
                                label='{0:s} {1:s}'.format(team, pptype))
                else:
                    ax2.axvspan(start, end, ymin=cf_at_time_min / ymax,
                                ymax=cf_at_time_max / ymax, alpha=0.5, facecolor=colors[team])
                ax2.axvspan(start, end + 1, ymin=0, ymax=0.05, alpha=0.5, facecolor=colors_to_use[team])

    # Set limits
    ax2.set_xlim(0, cf[hname].Time.max())
    ax2.set_ylim(0, ymax)
    ax.set_ylabel('Cumulative CF')
    plt.legend(loc=2, framealpha=0.5, fontsize=8)

    # Ticks every 10 min on bottom axis; none on top axis
    ax.set_xlim(0, cf[hname].Time.max() / 60)
    ax.set_xticks(range(0, cf[hname].Time.max() // 60 + 1, 10))
    ax.set_xlabel('Time elapsed in game (min)')
    ax2.set_xticks([])

    # Set title
    plt.title(_get_corsi_timeline_title(season, game))

    plt.gcf().canvas.set_window_title('{0:d} {1:d} TL.png'.format(season, game))

    if save_file is None:
        plt.show()
    elif save_file == 'fig':
        return plt.gcf()
github rasbt / python-machine-learning-book / code / optional-py-scripts / ch05.py View on Github external
print(50 * '=')
print('Section: Projecting samples onto the new feature space')
print(50 * '-')

X_train_lda = X_train_std.dot(w)
colors = ['r', 'b', 'g']
markers = ['s', 'x', 'o']

for l, c, m in zip(np.unique(y_train), colors, markers):
    plt.scatter(X_train_lda[y_train == l, 0] * (-1),
                X_train_lda[y_train == l, 1] * (-1),
                c=c, label=l, marker=m)

plt.xlabel('LD 1')
plt.ylabel('LD 2')
plt.legend(loc='lower right')
# plt.tight_layout()
# plt.savefig('./figures/lda2.png', dpi=300)
plt.show()


#############################################################################
print(50 * '=')
print('Section: LDA via scikit-learn')
print(50 * '-')

lda = LDA(n_components=2)
X_train_lda = lda.fit_transform(X_train_std, y_train)

lr = LogisticRegression()
lr = lr.fit(X_train_lda, y_train)
github pylada / pylada-light / crystal / defects / extract / __init__.py View on Github external
x.append((xlim[1]+5e0)*eV)

        # Now draws lines. 
        lines.append(lines[-1])
        if   defect.is_interstitial: linestyle, color =  '-', _colors[i % len(_colors)]
        elif defect.is_substitution: linestyle, color = '--', _colors[i % len(_colors)]
        elif defect.is_vacancy:      linestyle, color = '-.', _colors[i % len(_colors)]
        else:                        linestyle, color =  ':', _colors[i % len(_colors)]
        y = [u[0] + u[1] * xx for u, xx in zip(lines, x)]
        plt.plot(x, y, label=defect.latex_label, color=color, linestyle=linestyle, **kwargs)

      # plot vbm and cbm
      plt.axvline(material.vbm, color='black')
      plt.axvline(material.cbm, color='black')

      plt.legend()
      ylim = ylim[0] - (ylim[1]-ylim[0]) * 0.05, ylim[1] + (ylim[1]-ylim[0]) * 0.05
      xlim = xlim[0] - (xlim[1]-xlim[0]) * 0.05, xlim[1] + (xlim[1]-xlim[0]) * 0.05
      plt.xlim(xlim)
      plt.ylim(ylim)
      plt.xlabel("Fermi Energy [in eV]")
      plt.ylabel("$\Delta H_{D,q}(E_F)$ [in eV]")
      plt.draw()
github je-suis-tm / quant-trading / Oil Money project / oil production / oil production cost curve.py View on Github external
np.mean([min(cumwid),
                         max(cumwid)+list(wid)[-1]]),
                1.01*max(cumwid)+list(wid)[-1]])
    
    #if cost curve breakdown is provided
    #add legends to the right
    if len(y2)>0:
        plt.text(1.1*max(cumwid)+list(wid)[-1],
             list(y1)[-1]/2,notes[0],
                 verticalalignment='center', horizontalalignment='center')
        plt.text(1.1*max(cumwid)+list(wid)[-1],
             list(y1)[-1]+list(y2)[-1]/2,notes[1],
                verticalalignment='center', horizontalalignment='center')
    
    #legends of cost curve for different entities is plotted below the chart
    plt.legend(loc=6,bbox_to_anchor=(0.12, -0.4), ncol=4)    
    
    plt.show()
github jotterbach / dstk / DSTK / FeatureBinning / plotting.py View on Github external
def _plot_bucket_values(buckets, title=None, class_labels={0: '0', 1: '1'}):
    class_0 = [tup[1][0] for tup in buckets]
    class_1 = [tup[1][1] for tup in buckets]
    label = [str(tup[0]).replace(')', ']') for tup in buckets]
    ind = np.arange(len(class_0))
    w = 0.5
    plt.bar(ind, class_0, w, label=class_labels[0])
    plt.bar(ind, class_1, w, bottom=class_0, color='g', label=class_labels[1])
    plt.xticks(ind + w / 2., label, size=16, rotation=75)
    plt.yticks(size=16)
    plt.legend(fontsize=16)
    if title:
        plt.title(title, size=16)
    plt.xlabel('bucket', size=18)
    plt.ylabel('bucket value', size=18)
github je-suis-tm / quant-trading / Oil Money project / Oil Money NOK.py View on Github external
portfolio['total asset'].plot(c='#594f4f',alpha=0.5,label='Total Asset')
ax.plot(portfolio.loc[portfolio['signals']>0].index,portfolio['total asset'][portfolio['signals']>0],
         lw=0,marker='^',c='#2a3457',label='LONG',markersize=10,alpha=0.5)
ax.plot(portfolio.loc[portfolio['signals']<0].index,portfolio['total asset'][portfolio['signals']<0],
         lw=0,marker='v',c='#720017',label='The Big Short',markersize=15,alpha=0.5)
ax.fill_between(portfolio['2017-11-20':'2017-12-20'].index,
                 (portfolio['total asset']+np.std(portfolio['total asset']))['2017-11-20':'2017-12-20'],
                 (portfolio['total asset']-np.std(portfolio['total asset']))['2017-11-20':'2017-12-20'],
                 alpha=0.2, color='#547980')

plt.text(pd.to_datetime('2017-12-20'),
          (portfolio['total asset']+np.std(portfolio['total asset'])).loc['2017-12-20'],
          'What if we use MACD here?')
plt.axvline('2017/11/15',linestyle=':',label='Exit',c='#ff847c')
plt.legend()
plt.title('Portfolio Performance')
plt.ylabel('Asset Value')
plt.xlabel('Date')
plt.show()


#surprising when our model is valid for prediction
#its difficult to make money from thresholds oscillating
#when actual price goes beyond stop order boundary
#that is basically the most profitable trade ever
#best to follow up with a momentum strategy
#maybe this is not a statistical arbitrage after all
#the model is a trend following entry indicator


# In[17]:
github cagdasyigit / coursera-applied-machine-learning-with-python / Assignment+2.py View on Github external
def part1_scatter():
    import matplotlib.pyplot as plt
    get_ipython().magic('matplotlib notebook')
    plt.figure()
    plt.scatter(X_train, y_train, label='training data')
    plt.scatter(X_test, y_test, label='test data')
    plt.legend(loc=4);
github Networks-Learning / tpprl / tpprl_finance / plot_data.py View on Github external
# rl_df_sell['datetime'] = pd.to_datetime(rl_data_sell.t_i * 10 ** 9)
        # rl_df_sell['RL_sell'] = rl_data_sell.v_curr

        # common_buy = pd.merge(bollinger_df_buy, rl_df_buy, how='inner', on=['int_datetime'])

        # plot
        plt.plot_date(x=raw.datetime, y=raw.market, fmt='k-')

        plt.plot_date(x=bollinger_df_buy.datetime, y=bollinger_df_buy.Bollinger_buy, fmt='ro')
        plt.plot_date(x=bollinger_df_sell.datetime, y=bollinger_df_sell.Bollinger_sell, fmt='bo')

        # plt.plot_date(x=rl_df_buy.datetime, y=rl_df_buy.RL_buy, fmt='rx')
        # plt.plot_date(x=rl_df_sell.datetime, y=rl_df_sell.RL_sell, fmt='bx')

        # plt.plot_date(x=common_buy.datetime, y=common_buy.price, fmt='g^')
        plt.legend(loc='upper left')
        plt.xlabel("date")
        plt.ylabel("share price")
        plt.grid(True)

        # manager = plt.get_current_fig_manager()
        # manager.window.showMaximized()
        img_dir = SAVE_DIR+"/results_"+method+"_strategy/val_plots"
        if not os.path.exists(img_dir):
            os.makedirs(img_dir)
        plt.savefig(img_dir+"/{}_epoch_{}_day.png".format(epoch, file_num))
        plt.close()
github hartmetzls / audio_to_midi / check_robust.py View on Github external
callbacks=[checkpointer])
        test_score = model.evaluate(cqt_test, midi_test, verbose=0)
        print("test score:")
        print("[loss (rmse), root_mse, mae, r2_coeff_determination]")
        print(test_score)

        done_beep()

        # summarize history for loss
        # https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/
        plt.plot(history_for_plotting.history['loss'])
        plt.plot(history_for_plotting.history['val_loss'])
        plt.title('model loss')
        plt.ylabel('loss')
        plt.xlabel('epoch')
        plt.legend(['train rmse', 'validation rmse'], loc='upper right')
        plt.show()
github jcmgray / quimb / quimb / tensor / tensor_core.py View on Github external
edgecolors=node_outline_colors)
        nx.draw_networkx_labels(G, pos, labels, font_size=10, ax=ax)
        nx.draw_networkx_edges(G, pos, edge_color=edge_colors,
                               alpha=edge_alpha, width=edge_weights, ax=ax)

        # create legend
        if colors and legend:
            handles = []
            for color in colors.values():
                handles += [plt.Line2D([0], [0], marker='o', color=color,
                                       linestyle='', markersize=10)]

            # needed in case '_' is the first character
            lbls = [" {}".format(l) for l in colors]

            plt.legend(handles, lbls, ncol=max(int(len(handles) / 20), 1),
                       loc='center left', bbox_to_anchor=(1, 0.5))

        if return_fig:
            return fig
        else:
            plt.show()