Exemplo n.º 1
0
def get_line(datas, user_id):
    #datas按照时间逆序排序,即最近的在前面
    if os.path.exists("static/img/" + user_id + "/" + "line.png"):
        return "static/img/" + user_id + "/" + "line.png"
    num = len(datas) > 7 and 7 or len(datas)
    x = list(range(1, num + 1))
    #分三条线
    scene = [0] * 7
    person = [0] * 7
    animals = [0] * 7
    #从数据开始进行筛选
    for i in range(num):
        if datas[i][0] == '场景':
            scene[i] = random.random() * 5
        elif datas[i][0] == '人物':
            person[i] = random.random() * 5
        else:
            animals[i] = random.random() * 5
    plt.title('Result Analysis')
    plt.plot(x, scene, color='green', label='scene')
    plt.plot(x, person, color='blue', label='person')
    plt.plot(x, animals, color='red', label='animals')
    plt.set_size_inches(3, 2)
    plt.legend()
    # 显示图例
    plt.xlabel('latest videl')
    plt.ylabel('rate')
    plt.savefig("static/img/" + user_id + "/" + "line.png")
    return "static/img/" + user_id + "/" + "line.png"
Exemplo n.º 2
0
def define_strategy(X_train, y_train):
    """
    Identifies the best strategy for implementing the dummy classifier

    Parameters:
    ----------
    X_train: Subset of the original data set to be used as training set
    y_train: Labels corresponding to the X_train data set
    """

    plt = matplotlib.pyplot.gcf()
    plt.set_size_inches(12, 8)
    strats = ['stratified', 'most_frequent', 'prior', 'uniform', 'constant']
    train_dummy_scores = {}

    for clfs in strats:
        if clfs == 'constant':
            dummy_clf = DummyClassifier(strategy = clfs, random_state = 0, \
                                        constant = 0)
        else:
            dummy_clf = DummyClassifier(strategy=clfs, random_state=0)
        dummy_clf.fit(X_train, y_train)
        score = dummy_clf.score(X_train, y_train)
        train_dummy_scores[clfs] = score

    values = list(train_dummy_scores.values())
    ax = sns.stripplot(strats, values)
    ax.set(xlabel='strategy', ylabel='training score')
    plt.savefig('../plots/strategies.jpg')
    plt.clf()
Exemplo n.º 3
0
def draw_wavelet_transform():
    from scipy.interpolate import interp1d
    import scipy.fftpack
    from scipy import signal
    sensor_data = data = np.genfromtxt('./ICS_slipperData/Alice0105db.csv', dtype=float, delimiter=',', names=True)
    timestamp = sensor_data['Timestamp']
    signal = sensor_data['Axis1']

    sample_frequency = 500
    timestamp_sampled = np.arange(timestamp[0], timestamp[-1], 1.0/sample_frequency)
    f = interp1d(timestamp, signal, kind='slinear')
    signal_sample = f(timestamp_sampled)
    widths = np.arange(1, 200)
    cwtmatr = scipy.signal.cwt(scipy.fftpack.fft(f(timestamp_sampled)), scipy.signal.ricker, widths)
    print len(timestamp_sampled)
    print cwtmatr.shape
    plt.figure(figsize=(16, 6), dpi=100)
    plt.set_size_inches(8.27, 11.69)
    #plt.xticks(timestamp_sampled)
    plt.imshow(cwtmatr)
    #plt.show()
    plt.savefig('signal_cwt.png', dpi=600, bbox_inches='tight')
Exemplo n.º 4
0
def multiplotter(df, leftdict={}, rightdict={}, **kwargs):
    """
    Plot a big chart and its subplots together
    :param leftdict: a dict of arguments for the big plot
    :type leftdict: dict
    :param rightdict: a dict of arguments for the small plot
    :type rightdict: dict
    """
    from .table import Table

    axes = []

    df2 = rightdict.pop('data', df.copy())

    # add more cool layouts here
    # and figure out a nice way to access them other than numbers...
    from .layouts import layouts

    if isinstance(kwargs.get('layout'), list):
        layout = kwargs['layout']
    else:
        lay = kwargs.get('layout', 1)
        layout = layouts.get(lay)

    kinda = leftdict.pop('kind', 'area')
    kindb = rightdict.pop('kind', 'line')
    tpa = leftdict.pop('transpose', False)
    tpb = rightdict.pop('transpose', False)
    numtoplot = leftdict.pop('num_to_plot', len(layout) - 1)
    ntpb = rightdict.pop('num_to_plot', 'all')
    sharex = rightdict.pop('sharex', True)
    sharey = rightdict.pop('sharey', False)
    if kindb == 'pie':
        piecol = rightdict.pop('colours', 'default')
    coloursb = rightdict.pop('colours', 'default')
    fig = plt.figure()
    
    for i, (nrows, ncols, plot_number) in enumerate(layout, start=-1):
        if tpb:
            df2 = df2.T
        if i >= len(df2.columns):
            continue
        ax = fig.add_subplot(nrows, ncols, plot_number)
        if i == -1:
            df.chart(kind=kinda, ax=ax, transpose=tpa, num_to_plot=numtoplot, **leftdict)
            if kinda in ['bar', 'hist', 'barh']:
                import matplotlib as mpl
                colmap = []
                rects = [r for r in ax.get_children() if isinstance(r, mpl.patches.Rectangle)]
                for r in rects:
                    if r._facecolor not in colmap:
                        colmap.append(r._facecolor)
                try:
                    colmap = {list(df.columns)[i]: x for i, x in enumerate(colmap[:len(df.columns)])}
                except AttributeError:
                    colmap = {list(df.index)[i]: x for i, x in enumerate(colmap[:len(df.index)])}
            else:
                try:
                    colmap = {list(df.columns)[i]: l.get_color() for i, l in enumerate(ax.get_lines())}
                except AttributeError:
                    colmap = {list(df.index)[i]: l.get_color() for i, l in enumerate(ax.get_lines())}
        else:
            if colmap and kindb != 'pie':
                try:
                    name = df2.iloc[:, i].name
                    coloursb = colmap[name]
                except IndexError:
                    coloursb = 'gray'
                except KeyError:
                    coloursb = 'gray'

            if kindb == 'pie':
                rightdict['colours'] = piecol
            else:
                rightdict['colours'] = coloursb

            Table(df2.iloc[:, i]).chart(kind=kindb, ax=ax, sharex=sharex, sharey=sharey,
                                     num_to_plot=ntpb, **rightdict)
            ax.set_title(df2.iloc[:, i].name)
        
    wspace = kwargs.get('wspace', .2)
    hspace = kwargs.get('hspace', .5)

    fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975, wspace=wspace, hspace=hspace)

    size = kwargs.get('figsize', (10, 4))
    fig.set_size_inches(size)
    try:
        plt.set_size_inches(size)
    except:
        pass
    if kwargs.get('save'):
        savepath = os.path.join('images', kwargs['save'] + '.png')
        fig.savefig(savepath, dpi=150)
    return plt
Exemplo n.º 5
0
FangShui=['Bawal','Chennai','Roorkee','T-16 Auto','Auto']
dcf5=pd.DataFrame()
for i in range(5):
    if i==4:
        abhikeliye=df.loc[FangShui[i]:,:]
    else:
        abhikeliye=df.loc[FangShui[i]:FangShui[i+1],:]
    abhikeliye=abhikeliye.iloc[7,:]
    abhikeliye=abhikeliye.iloc[:48]
    abhikeliye=abhikeliye.astype(str).astype(float).apply(np.int64)
    abhikeliye.index = pd.date_range(start='4/1/2015', periods=len(data), freq='M')
    abhikeliye.plot()
    plt.ylabel("Productivity per Person per plant", fontsize=18)
    plt.xlabel("Months", fontsize=18)
    plt.tight_layout()
    plt.set_size_inches(18.5, 10.5, forward=True)
    if 'pdf' in option:
        plt.savefig('download/foo4.pdf', bbox_inches='tight',dpi=200)
    if 'eps' in option:
        plt.savefig('download/foo4.eps', bbox_inches='tight',dpi=200)
    if 'png' in option:
        plt.savefig('download/foo4.png', bbox_inches='tight', dpi=200)
    dcf5=pd.concat([dcf5,abhikeliye], axis=1)
    
dcf5.plot()
plt.legend(labels=FangShui,loc=2, prop={'size': 5})
plt.ylabel("Productivity per Person per plant", fontsize=11)
plt.xlabel("Months", fontsize=11)
option=['png','pdf','eps']
if 'pdf' in option:
    plt.savefig('download/hoo4.pdf', bbox_inches='tight',dpi=200)
Exemplo n.º 6
0
df_july.rolling(5).mean().plot(ax=ax)
df_aug.rolling(5).mean().plot(ax=ax)
plt.grid()
plt.legend(['NAO May', 'NAO June', 'NAO July', 'NAO August'])



ax = df_JJA.rolling(5).mean().plot()
df_JJ.rolling(5).mean().plot(ax=ax)
plt.grid()
plt.legend(['NAO JJA', 'NAO JJ']) 



ax = df_JJ.plot(color='k', linewidth=.5, zorder=10)
ax.fill_between([df_JJ.index[0], df_JJ.index[-1]], 0, [2, 2], color='steelblue', alpha=.4)
ax.fill_between([df_JJ.index[0], df_JJ.index[-1]], 0, [-2, -2], color='indianred', alpha=.4)
df_JJ.rolling(5).mean().plot(ax=ax, color='dimgray', linewidth=3, zorder=10)
plt.grid()
plt.title('NAO June-July')
plt.ylim([-1.5, 1.5])
plt.xlabel(None)
ax.get_legend().remove()
plt.set_size_inches(w=15, h=10)
plt.savefig('NAO_JJ.png', dpi=200)

# Save csv
df_JJ.index = df_JJ.index.year
df_JJ.to_csv('NAO_June-July.csv', float_format='%.2f')
df_JJ.rolling(5).mean().to_csv('NAO_June-July_5yr_rolling_mean.csv', float_format='%.2f')
Exemplo n.º 7
0
def multiplotter(df, leftdict={},rightdict={}, **kwargs):
    """
    Plot a big chart and its subplots together
    :param leftdict: a dict of arguments for the big plot
    :type leftdict: dict
    :param rightdict: a dict of arguments for the small plot
    :type rightdict: dict
    
    """
    from corpkit.interrogation import Interrogation
    import matplotlib.pyplot as plt
    axes = []

    if isinstance(df, Interrogation):
        df = df.results

    df2 = rightdict.pop('data', df.copy())
    if isinstance(df2, Interrogation):
        df2 = df2.results

    # add more cool layouts here
    # and figure out a nice way to access them other than numbers...
    from corpkit.layouts import layouts

    if isinstance(kwargs.get('layout'), list):
        layout = kwargs.get('layout')
    else:
        lay = kwargs.get('layout', 1)
        layout = layouts.get(lay)

    kinda = leftdict.pop('kind', 'area')
    kindb = rightdict.pop('kind', 'line')
    tpa = leftdict.pop('transpose', False)
    tpb = rightdict.pop('transpose', False)
    numtoplot = leftdict.pop('num_to_plot', len(layout) - 1)
    ntpb = rightdict.pop('num_to_plot', 'all')
    sharex = rightdict.pop('sharex', True)
    sharey = rightdict.pop('sharey', False)
    if kindb == 'pie':
        piecol = rightdict.pop('colours', 'default')
    coloursb = rightdict.pop('colours', 'default')
    fig = plt.figure()
    
    for i, (nrows, ncols, plot_number) in enumerate(layout, start=-1):
        if tpb:
            df2 = df2.T
        if i >= len(df2.columns):
            continue
        ax = fig.add_subplot(nrows, ncols, plot_number)
        if i == -1:
            df.visualise(kind=kinda, ax=ax, transpose=tpa,
                         num_to_plot=numtoplot, **leftdict)
            if kinda in ['bar', 'hist', 'barh']:
                import matplotlib as mpl
                colmap = []
                rects = [r for r in ax.get_children() if isinstance(r, mpl.patches.Rectangle)]
                for r in rects:
                    if r._facecolor not in colmap:
                        colmap.append(r._facecolor)
                colmap = {list(df.columns)[i]: x for i, x in enumerate(colmap[:len(df.columns)])}
            else:
                colmap = {list(df.columns)[i]: l.get_color() for i, l in enumerate(ax.get_lines())}
        else:
            if colmap and kindb != 'pie':
                try:
                    name = df2.iloc[:, i].name
                    coloursb = colmap[name]
                except IndexError:
                    coloursb = 'gray'
                except KeyError:
                    coloursb = 'gray'

            if kindb == 'pie':
                rightdict['colours'] = piecol
            else:
                rightdict['colours'] = coloursb

            df2.iloc[:, i].visualise(kind=kindb, ax=ax, sharex=sharex, sharey=sharey,
                                     num_to_plot=ntpb, **rightdict)
            ax.set_title(df2.iloc[:, i].name)
        
    wspace = kwargs.get('wspace', .2)
    hspace = kwargs.get('hspace', .5)

    fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975,
                        wspace=wspace, hspace=hspace)

    size = kwargs.get('figsize', (10, 4))
    fig.set_size_inches(size)
    try:
        plt.set_size_inches(size)
    except:
        pass
    if kwargs.get('save'):
        import os
        from corpkit.process import urlify
        savepath = os.path.join('images', urlify(kwargs['save']) + '.png')
        fig.savefig(savepath, dpi=150)
    return plt