Пример #1
0
def plot_data_mlp_to_html(data_points, labels=[]):
    # print(len(dataPoints))
    data_points = cull_to_number(data_points, 250)
    # print(len(dataPoints))
    # print(dataPoints)
    swap = swapaxes(data_points, 0, 1)
    # print(swap)
    timescale = []
    for i, date in enumerate(swap[0]):
        parsedDate = datetime.datetime.strptime(date, '%m/%d/%y %H:%M:%S')
        timescale.append(parsedDate)
    # timescale = [datetime.datetime.strptime(date, '%m/%d/%y %H:%M:%S') for date in swap[0]]
    dates = matplotlib.dates.date2num(timescale)
    fig, ax = plt.subplots(figsize=[9.28, 4.8])
    plt.rcParams.update({'figure.autolayout': True})
    ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10))
    ax.grid(which='major', axis='both', linestyle="-", alpha=0.25, linewidth=1)
    ax.tick_params(labelsize='medium', width=1)
    # Read labels from list
    p1 = ax.plot_date(dates,
                      swap[1],
                      color='red',
                      linestyle='solid',
                      marker=None,
                      label=labels[0])
    p2 = ax.plot_date(dates,
                      swap[2],
                      color='green',
                      linestyle='solid',
                      marker=None,
                      label=labels[1])
    p3 = ax.plot_date(dates,
                      swap[3],
                      color='blue',
                      linestyle='solid',
                      marker=None,
                      label=labels[2])
    s1 = ax.scatter(dates, swap[1], color='#00000000', s=50)
    s2 = ax.scatter(dates, swap[2], color='#00000000', s=50)
    s3 = ax.scatter(dates, swap[3], color='#00000000', s=50)
    ax.legend()
    # xlabels = ax.get_xticklabels()
    # plt.setp(xlabels, rotation=30, horizontalalignment='right')
    ax.set(ylim=[0, 100],
           xlabel='Dată',
           ylabel='Procent (%)',
           title='Grafic umiditate plante')

    # Create HTML
    plugins.clear(fig)
    tooltip_plugin1 = plugins.PointLabelTooltip(
        s1, extract_point_position(swap[0], swap[1]))
    tooltip_plugin2 = plugins.PointLabelTooltip(
        s2, extract_point_position(swap[0], swap[2]))
    tooltip_plugin3 = plugins.PointLabelTooltip(
        s3, extract_point_position(swap[0], swap[3]))
    plugins.connect(fig, tooltip_plugin1, tooltip_plugin2, tooltip_plugin3,
                    plugins.Zoom(), plugins.Reset())
    html_str = fig_to_html(fig)
    return html_str
Пример #2
0
def plot_topics_mpld3(H, tweet_dict):
    '''
    INPUT
         - H topic matrix from NMF
         - tweet_dict - dictionary of tweet information
            which includes:
                the most important tweet
                the percent of tweets that fall into a certain topic
                the sentence important of each tweet under each topic
                the top words
    OUTPUT
         - creates a plot using mpl3d

    Returns nothing
    '''
    pca = PCA(n_components=2)
    hflat = pca.fit_transform(H)
    xs, ys = hflat[:, 0], hflat[:, 1]
    topic_size = tweet_dict['topic_size_pct']
    cluster_names = tweet_dict['top_words']
    titles = tweet_dict['exemplary_tweet']
    clusdf = pd.DataFrame(dict(x=xs, y=ys, label=range(hflat.shape[0])))
    clusdf['title'] = clusdf['label'].apply(lambda label: titles[label])
    fig, ax = plt.subplots(figsize=(17, 9))
    ax.margins(0.03)
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * .8, box.height])
    for name, x, y in zip(clusdf.label.values, clusdf.x.values,
                          clusdf.y.values):
        points = ax.plot(x,
                         y,
                         marker='o',
                         linestyle='',
                         ms=topic_size[name],
                         label=cluster_names[name])
        ax.set_aspect('auto')
        ax.axes.get_xaxis().set_ticks([])
        ax.axes.get_yaxis().set_ticks([])
        ax.axes.get_xaxis().set_visible(False)
        ax.axes.get_yaxis().set_visible(False)
        tooltip = \
            plugins.PointLabelTooltip(points[0],
                                      labels=[clusdf.title.values[name]])
        plugins.connect(fig, tooltip)
    ax.set_xlabel('PC 1')
    ax.set_ylabel('PC 2')
    # for i in range(len(clusdf)):
    #     ax.text(clusdf.ix[i]['x'], clusdf.ix[i]['y'],
    #             clusdf.ix[i]['title'], size=12)
    lgnd = ax.legend(loc='center left',
                     bbox_to_anchor=(1, 0.5),
                     numpoints=1,
                     title='Top Words Used in the Topics',
                     frameon=False,
                     markerscale=1)
    for i in range(H.shape[0]):
        lgnd.legendHandles[i]._legmarker.set_markersize(12)
        lgnd.legendHandles[i]._legmarker.set_markersize(12)
    # plt.show()
    mpld3.show()
Пример #3
0
def main():
    fig, ax = plt.subplots()
    points = ax.plot(range(10), 'o', ms=20)
    plugins.connect(fig,
                    plugins.PointLabelTooltip(points[0], location="top left"))

    return fig
Пример #4
0
def main():
    fig, ax = plt.subplots()
    colors = plt.rcParams['axes.color_cycle']
    points = []
    for i, color in enumerate(colors):
        points = ax.plot(i, 0, 'o', c=color, ms=20)
        plugins.connect(fig, plugins.PointLabelTooltip(points[0], [color]))
    ax.set_xlim(-1, len(colors) + 1)

    return fig
Пример #5
0
def distributionGraph(filename, outputname):
    #function to obtain the interactive gene frequency graph for the pangenome, in html
    genes = []
    coreSize = 0
    isolates = []
    with open(filename, 'r') as fh:

        reader = csv.reader(fh, delimiter='\t')
        isolates = reader.next()[1:]

        for row in reader:
            geneName = row[0]
            numbers = [int(x) for x in row[1:]]
            freq = sum(numbers)
            genes.append((geneName, freq))
            if freq == len(isolates):
                coreSize += 1
    genes.sort(key=lambda tup: tup[1], reverse=True)
    x = []
    y = []
    xLabels = []

    for item in genes:
        y.append(item[1])
        x.append(genes.index(item))
        xLabels.append(item[0])

    fig, ax = plt.subplots(figsize=(12, 9))

    line = ax.plot(x, y, '.', color="#3F5D7D")
    plt.title("Pan-Genome Frequency")
    plt.ylabel('Frequency')
    plt.xlabel('Gene')
    plt.text(
        1.1,
        0.9,
        s="%s Isolates | Pan-Genome: %s genes | Core Genome: %s genes | Acessory Genome: %s genes"
        % (str(len(isolates)), str(
            len(genes)), str(coreSize), str(len(genes) - coreSize)),
        fontsize=10,
        horizontalalignment='right',
        verticalalignment='center',
        transform=ax.transAxes)
    ax.yaxis.labelpad = 40

    mpld3.plugins.connect(fig,
                          plugins.PointLabelTooltip(line[0], labels=xLabels))

    mpld3.save_html(fig, outputname)
Пример #6
0
def main():
    fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
    N = 100

    scatter = ax.scatter(np.random.normal(size=N),
                         np.random.normal(size=N),
                         c=np.random.random(size=N),
                         s = 1000 * np.random.random(size=N),
                         alpha=0.3,
                         cmap=plt.cm.jet)
    ax.grid(color='white', linestyle='solid')

    ax.set_title("Scatter Plot (with tooltips!)", size=20)

    labels = ['point {0}'.format(i + 1) for i in range(N)]
    tooltip = plugins.PointLabelTooltip(scatter, labels=labels)
    plugins.connect(fig, tooltip)

    return fig
def show_tsne():
    np_rep = np.array(reps)
    tenth = len(labels) // 10
    X = np_rep[:tenth, :, :]
    tsne = TSNE(n_components=2, init='random')
    np_corr = np.array(corrects[:tenth])
    mark_col = np.zeros_like(np_corr)
    mark_col[np_corr] = 1
    np_lbls = np.array(labels[:tenth])
    num_heads = X.shape[1]
    tX = np.zeros((tenth, num_heads, 2))
    #dumb = np.arange(tenth, dtype=np.float)/tenth
    #dumb = dumb.reshape((-1,1))
    fig, ax = plt.subplots(num_heads // 2, 6, figsize=(24, 12))
    for i in range(num_heads):
        tX[:, i, :] = tsne.fit_transform(X[:, i, :])
    #print(tX[:10,:])
    tips = np_lbls.tolist()
    for i in range(num_heads):
        points = ax[i // 2, i % 2].scatter(tX[:, i, 0],
                                           tX[:, i, 1],
                                           c=mark_col,
                                           s=30,
                                           edgecolors='k',
                                           alpha=0.6)
        tooltip = plugins.PointLabelTooltip(points, labels=tips)
        plugins.connect(fig, tooltip)
        points = ax[i // 2, (i % 2) + 2].scatter(tX[:, i, 0],
                                                 tX[:, (i + 1) % num_heads, 0],
                                                 alpha=0)
        points = ax[i // 2, (i % 2) + 4].scatter(tX[:, i, 0],
                                                 tX[:, (i + 2) % num_heads, 1],
                                                 alpha=0)
    #for i, txt in enumerate(labels[:680]):
    #    ax.annotate(txt, (tX[i,0], tX[i,1]))

    plugins.connect(fig, plugins.LinkedBrush(points))
    #chart = json.dumps(mpld3.fig_to_dict(fig))
    #ax.legend()
    mpld3.show()
    #return mpld3.fig_to_html(fig)
    return render_template('clusters.html', chart=chart)
Пример #8
0
    def __generatehtml(self, fig):
        i = 0
        for ax in fig.get_axes():
            plugins.connect(
                fig,
                plugins.InteractiveLegendPlugin(
                    plot_elements=ax.get_lines(),
                    labels=[str(x) for x in ax.get_legend().get_texts()],
                    ax=ax,
                    alpha_unsel=0.0,
                    alpha_over=1.5))
            i += 1
            for line in ax.get_lines():
                line.set_ydata(
                    [x if x is not None else 0 for x in line.get_ydata()])
                plugins.connect(
                    fig,
                    plugins.PointLabelTooltip(
                        points=line,
                        labels=[str(y) for y in line.get_ydata()],
                        hoffset=10,
                        voffset=10))

        return mpld3.fig_to_html(fig)
def func(ra, dec, mag, fov):

    # sorting objects under the user input of limiting magnitude

    mag_ng = ng[(ng["V"] <= mag)]
    mag_ms = ms[(ms['V'] <= mag)]
    mag_ty1 = ty1[(ty1['V'] <= mag)]
    mag_ty2 = ty2[(ty2['V'] <= mag)]

    # breathing space around the fov circle in the plot
    xl = ra - fov / 2 - fov / 10
    xr = ra + fov / 2 + fov / 10
    yb = dec - fov / 2 - fov / 10
    yt = dec + fov / 2 + fov / 10

    fig, ax = plt.subplots(figsize=(15, 7))
    ax.set_xlabel('Right Ascension (degrees)', fontsize=20)
    ax.set_ylabel('Declination (degrees)', fontsize=20)
    ax.scatter(ra, dec, s=50, marker='P', color='yellow', zorder=10)

    # sorting objects in messier_objects.csv according to objects
    cl_ms = ms[(ms["TYPE"] == 'OpC') | (ms["TYPE"] == 'GlC') |
               (ms["TYPE"] == 'Cl*')]
    pn_ms = ms[(ms["TYPE"] == 'PN')]
    ga_ms = ms[(ms["TYPE"] == 'G') | (ms["TYPE"] == 'Sy2') |
               (ms["TYPE"] == 'IG') | (ms["TYPE"] == 'GiG') |
               (ms["TYPE"] == 'GiP') | (ms["TYPE"] == 'SyG') |
               (ms["TYPE"] == 'SBG') | (ms["TYPE"] == 'BiC') |
               (ms["TYPE"] == 'H2G')]
    re_ms = ms[(ms["TYPE"] == 'HII') | (ms["TYPE"] == 'As*') |
               (ms["TYPE"] == 'LIN') | (ms["TYPE"] == 'mul') |
               (ms["TYPE"] == 'RNe') | (ms["TYPE"] == 'AGN')]

    print(
        f"Observing RA: {ra} deg, DEC: {dec} deg, FoV: {fov} deg, Limiting Magnitude: {mag}"
    )

    ax.set_axisbelow(True)
    ax.minorticks_on()
    ax.grid(which='major', alpha=0.3)
    ax.grid(which='minor',
            linestyle=':',
            linewidth='0.5',
            color='black',
            alpha=0.3)
    ax.set_facecolor('teal')

    # scatter messier
    mag = cl_ms["V"].fillna(1)
    flux = 10**(-mag / 2.5)
    p1 = ax.scatter(cl_ms['RAJ2000'],
                    cl_ms['DEJ2000'],
                    color='darkorange',
                    s=17,
                    zorder=10,
                    edgecolor="black")
    l1 = [
        "[RA {0:.5f} \v DEC {1:.5f} \v Constellation {2} \v Name {3}]".format(
            i, j, k, l, '.2f', '.2f', '%s', '%s')
        for i, j, k, l in zip(cl_ms['RAJ2000'], cl_ms['DEJ2000'],
                              cl_ms['Constellation'], cl_ms["Common Name"])
    ]
    t1 = plugins.PointLabelTooltip(p1, l1)
    plugins.connect(fig, t1)

    mag = pn_ms["V"].fillna(1)
    flux = 10**(-mag / 2.5)
    p2 = ax.scatter(pn_ms['RAJ2000'],
                    pn_ms['DEJ2000'],
                    color='blue',
                    s=17,
                    zorder=10,
                    edgecolor="black")
    l2 = [
        "[RA {0:.5f} \v DEC {1:.5f} \v Constellation {2} \v Name {3}]".format(
            i, j, k, l, '.2f', '.2f', '%s', '%s')
        for i, j, k, l in zip(pn_ms['RAJ2000'], pn_ms['DEJ2000'],
                              pn_ms['Constellation'], pn_ms["Common Name"])
    ]
    t2 = plugins.PointLabelTooltip(p2, l2)
    plugins.connect(fig, t2)

    mag = ga_ms["V"].fillna(1)
    flux = 10**(-mag / 2.5)
    p3 = ax.scatter(ga_ms['RAJ2000'],
                    ga_ms['DEJ2000'],
                    color='red',
                    s=17,
                    zorder=20,
                    edgecolor="black")
    l3 = [
        "[RA {0:.5f} \v DEC {1:.5f} \v Constellation {2} \v Name {3}]".format(
            i, j, k, l, '.2f', '.2f', '%s', "%s")
        for i, j, k, l in zip(ga_ms['RAJ2000'], ga_ms['DEJ2000'],
                              ga_ms['Constellation'], ga_ms["Common Name"])
    ]
    t3 = plugins.PointLabelTooltip(p3, l3)
    plugins.connect(fig, t3)

    mag = re_ms["V"].fillna(1)
    flux = 10**(-mag / 2.5)
    p4 = ax.scatter(re_ms['RAJ2000'],
                    re_ms['DEJ2000'],
                    c='darkmagenta',
                    s=17,
                    edgecolor="black")
    l4 = [
        "[RA {0:.5f} \v DEC {1:.5f} \v Constellation {2} \v Name {3}]".format(
            i, j, k, l, '.2f', '.2f', '%s', '%s')
        for i, j, k, l in zip(re_ms['RAJ2000'], re_ms['DEJ2000'],
                              re_ms['Constellation'], re_ms["Common Name"])
    ]
    t4 = plugins.PointLabelTooltip(p4, l4)
    plugins.connect(fig, t4)

    # scatter ngc
    mag = mag_ng['V'].fillna(1)
    flux = 10**(-mag / 2.5)
    p5 = ax.scatter(mag_ng['RAJ2000'],
                    mag_ng['DEJ2000'],
                    c='darkmagenta',
                    s=80 * flux)
    l5 = [
        "[RA {0:.5f} \v DEC {1:.5f} \v Constellation {2} \v Name {3}]".format(
            i, j, k, l, '.2f', '.2f', '%s', '%s')
        for i, j, k, l in zip(mag_ng['RAJ2000'], mag_ng['DEJ2000'],
                              mag_ng['Constellation'], mag_ng['Name'])
    ]
    t5 = plugins.PointLabelTooltip(p5, l5)
    plugins.connect(fig, t5)

    # scatter tycho-1
    mag = mag_ty1['V'].fillna(1)
    flux = 10**(-mag / 2.5)
    p6 = ax.scatter(mag_ty1['RAJ2000'],
                    mag_ty1['DEJ2000'],
                    c='white',
                    s=80 * flux)
    l6 = [
        "[RA {0:.5f} \v DEC {1:.5f} \v Constellation {2} \v Name {3}]".format(
            i, j, k, l, '.2f', '.2f', '%s', '%s')
        for i, j, k, l in zip(mag_ty1['RAJ2000'], mag_ty1['DEJ2000'],
                              mag_ty1['Constellation'], mag_ty1['Name'])
    ]
    t6 = plugins.PointLabelTooltip(p6, l6)
    plugins.connect(fig, t6)

    # scatter tycho-2
    # mag = mag_ty2['V'].fillna(1)
    # flux = 10**(-mag/2.5)
    # p7 = ax.scatter(mag_ty2['RAJ2000'], mag_ty2['DEJ2000'], c='white', s= 80*flux)
    # l7 = ["[RA {0:.5f} \v DEC {1:.5f} \v Constellation {2} ]".format(i,j,k,'.2f','.2f','%s') for i,j,k in zip(mag_ty2['RAJ2000'],mag_ty2['DEJ2000'],mag_ty2['Constellation'])]
    # t7 = plugins.PointLabelTooltip(p7,l7)
    # plugins.connect(fig, t7)

    points = [p1, p2, p3, p4, p5, p6]
    labels = [l1, l2, l3, l4, l5, l6]
    plugins.connect(fig, ClickInfo(points, labels))

    # constellation borders
    for i in cb['Constellation'].unique():
        x = cb[(cb['Constellation'] == i)]['RAJ2000']
        y = cb[(cb['Constellation'] == i)]['DEJ2000']
        x1 = x.mean()
        y1 = y.mean()
        ax.scatter(x, y, color='darkgreen', s=20 / fov)
        ax.annotate('%s' % i, (x1, y1), size=13)

    ax.add_artist(plt.Circle((ra, dec), color='#00af08', zorder=1, alpha=0.5))
    # ax.set_xlim([xl,xr])
    # ax.set_ylim([yb,yt])

    cluster = mlines.Line2D([], [],
                            color='darkorange',
                            marker=cl,
                            linestyle='None',
                            markersize=15,
                            label='Clusters',
                            markeredgecolor="black")
    planetary_neb = mlines.Line2D([], [],
                                  color='blue',
                                  marker=cl,
                                  linestyle='None',
                                  markersize=15,
                                  label='Planetary Nebula',
                                  markeredgecolor="black")
    galaxy = mlines.Line2D([], [],
                           color='Red',
                           marker=cl,
                           linestyle='None',
                           markersize=15,
                           label='Galaxies',
                           markeredgecolor="black")
    other = mlines.Line2D([], [],
                          color='darkmagenta',
                          marker=cl,
                          linestyle='None',
                          markersize=15,
                          label='Other NGC/Messier',
                          markeredgecolor="black")
    stars = mlines.Line2D([], [],
                          color='white',
                          marker=cl,
                          linestyle='None',
                          markersize=15,
                          label='Stars',
                          markeredgecolor="black")
    plt.legend(handles=[cluster, planetary_neb, galaxy, other, stars],
               labelspacing=2,
               ncol=5,
               borderpad=1,
               loc='lower center')

    mpld3.show()
Пример #10
0
def make_figure(figANDax,sample_data):
    fig,ax,fig2,ax2=figANDax
    with open('tp','rb') as f:  # Python 3: open(..., 'rb')
        hdist, tst_data = pickle.load(f)
        hdist = np.array(hdist).reshape([512,512]);

    col=[];
    # data=np.array([[]]);np.array()
    tst_data=np.array(tst_data)
    tst_data=tst_data;
    cm=plt.cm.rainbow
    col=col+list(cm(.01) for i in range(tst_data.shape[0]));

    sample_data=np.array(sample_data)
    col+=list(cm(.9) for i in range(sample_data.shape[0]));
    data=np.vstack((tst_data,sample_data));



    xs=data[:,3];
    xs=xs.astype(np.float)
    xs[np.isnan(xs)]=0;
    ys=(data[:,4].astype(np.float));
    # ys[ys==0]=1;
    # ys=np.log(ys);
    ys[~np.isfinite(ys)]=0;
    zs=(data[:,5].astype(np.float));
    zs[~np.isfinite(zs)]=0;


    sizs=list((.6-float(x))/.00755 for x in data[:,5])
    N = xs.size;
    labels=list(data[:,1]);
    # labels=data[:,[0,1,3]].T.to_html



    # fig, ax = plt.subplots(subplot_kw=dict(axisbg='#DDDDDD'
    #                                        ,projection='3d'
                                          # ))
    fig.set_size_inches([5,4])
    ax.grid(color='white', linestyle='solid')
    ax.set_ylim(0,0.38)
    ax.set_xlim(0,1)
    put_patches(ax)
    sct = ax.scatter(xs,
                     ys,
                     c=col,                
                     s = sizs,
                     alpha=1.0,
    #                      label=labels,
                         cmap=plt.cm.rainbow)
    red_patch = mpatches.Patch(color=plt.cm.rainbow(.98), label='The red data')
    pur_patch = mpatches.Patch(color=plt.cm.rainbow(.02), label='The red data')
    yel_patch = mpatches.Patch(color=plt.cm.rainbow(.02), label='The red data')
    handles, leglabels = ax.get_legend_handles_labels()
    handles +=[red_patch,pur_patch];
    leglabels +=['sample','reference'];
    ax.legend(handles,leglabels)
    ax.set_title("Dynamic landscape, 2D projection", size=20)
    plugins.connect(fig, 
                    plugins.PointLabelTooltip(sct, labels),
    #                 plugins.Zoom(enabled=False),
                    ClickInfo(sct,labels)
                   )
    ax.set_xlabel('Avg Temp',size=15);
    ax.set_ylabel('mean(abs(d_Temp)) - abs(mean(d_Temp))',size=15);
    
    sct3d = ax2.scatter(xs,
                         ys,
                     zs,
                        c=col,
    #                      c=list( 1.*float(i)/N for i in xs),
                         s = sizs,
                         alpha=1.0,
    #                      label=labels,
                         cmap=plt.cm.rainbow)
    ax2.set_title("Dynamic landscape, 3D", size=20)
    ax2.set_xlabel('Avg Temp',size=15);
    ax2.set_ylabel('mean(abs(d_Temp)) - abs(mean(d_Temp))',size=15);
    ax2.set_zlabel('Density of dominating state',size=15);
#    mpld3.display(fig)
    return( fig,ax,fig2,ax2)
Пример #11
0
x = np.linspace(0, 10, 5120/2.)

data = np.array([[x, Ai * np.sin(x / Pi)] for (Ai, Pi) in zip(A, P)])
data[:,1,:] = x2[:,0,::2]*20
print data.shape
A = np.random.randn(301)
A = dataobj.features[:,3]
P = np.arange(301)

points = ax2.scatter(P, A, s =50, alpha=0.5, c = dataobj.label_colarray)
#points = radviz2(df,'Network States',dataobj, ax = ax, color = cmap, edgecolor = 'white')
ax2.set_xlabel('Feature 2')
ax2.set_ylabel('Feature 1')

# create the line object
lines = ax1.plot(x, 0 * x, '-w', lw=1, alpha=0.8)
ax1.set_ylim(-1, 1)

ax1.set_title("Hover over points to see lines")

# transpose line data and add plugin
linedata = data.transpose(0, 2, 1).tolist()


labels = ["Trace {0}".format(i) for i in range(301)]
tooltip = plugins.PointLabelTooltip(points, labels)

plugins.connect(fig,LinkedView(points, lines[0], linedata))
plugins.connect(fig, ClickInfo(points))
#plugins.connect(fig,tooltip)
mpld3.display()
Пример #12
0
def visualize(model, title='Command confusion map'):
    records = []
    for nlpNode in model.nlpNodes:
        id = nlpNode.cliNode.id
        group = nlpNode.cliNode.group
        for query in nlpNode.nlpQueries:
            if query.has_vector and query.text == id:
                record = {
                    'vector': query.vector,
                    'command': id,
                    'query': query.text,
                    'group': group
                }
                records.append(record)

    embeddings = pd.DataFrame(records)

    tsne = TSNE(n_components=2,
                verbose=2,
                metric='cosine',
                method='exact',
                n_iter=5000,
                perplexity=20,
                random_state=1131)
    tsne_results = tsne.fit_transform(np.stack(embeddings.vector, axis=0))
    dfg = embeddings[['command', 'query', 'group']].copy()
    dfg['t-x'] = tsne_results[:, 0]
    dfg['t-y'] = tsne_results[:, 1]
    dfg['rank'] = (dfg['t-x'] - dfg['t-x'].min())**2 + (dfg['t-y'] -
                                                        dfg['t-y'].min())**2
    commandGroups = dfg.drop_duplicates(['group']).sort_values(
        ['rank'])[['group']].reset_index(drop=True)
    commandGroups['id'] = np.arange(0, len(commandGroups), 1)
    dfg = dfg.merge(commandGroups, on='group', how='inner')

    fig, ax = plt.subplots(figsize=(16, 12))
    ax.set_facecolor('#7E7E7E')
    colors = cm.tab20.colors
    for cmd in commandGroups['group']:
        data = dfg[dfg['group'] == cmd]
        c = data['id'].apply(lambda x: colors[x % len(colors)])
        s = data['group'].apply(lambda x: 50 if x == cmd else 10)
        pt = ax.scatter(data['t-x'],
                        data['t-y'],
                        c=c,
                        label=cmd,
                        s=s,
                        alpha=0.7)
        labels = [
            "- %s | %s" % (a[0], a[1])
            for a in zip(data['group'], data['query'])
        ]
        tooltip = plugins.PointLabelTooltip(pt, labels=labels)
        mpld3.plugins.connect(fig, tooltip)

    ax.grid(color='white', linestyle='solid')
    chartBox = ax.get_position()
    ax.set_position(
        [chartBox.x0, chartBox.y0, chartBox.width * 0.7, chartBox.height])
    lg = ax.legend(loc='upper left',
                   bbox_to_anchor=(1, 1.1),
                   ncol=1,
                   fancybox=0,
                   prop={
                       'family': 'Arial',
                       'size': '14'
                   })
    lg.set_title('Command groups', prop={'family': 'Arial', 'size': '16'})
    for i, text in enumerate(lg.get_texts()):
        text.set_color(colors[i % len(colors)])
    ax.set_title(title, size=20)
    plt.savefig('visualizer/' + title.replace(' ', '_') + '.pdf')
    # mpld3.save_html(fig, 'ConfusionMap.html')

    # import socket
    # import os
    # hostip=socket.gethostbyname(socket.gethostname())
    # if os.getenv("WIN-DOCKER") is None:
    #   hostip="0.0.0.0"
    # mpld3.show(ip=hostip)


# visualize(modelFactory.getBaselineModel_sm(), 'Command confusion map - small dataset with small model')
# visualize(modelFactory.getBaselineModel(), 'Command confusion map - large dataset with large model')
# visualize(modelFactory.getBaselineModel_partial(), 'Command confusion map - partial dataset with large model (commands only)')
# visualize(modelFactory.getModelWithAbbrQR_partial(), 'Command confusion map - partial dataset with large model with abbr QR (commands only)')
Пример #13
0
# <codecell>

# support for Chinese Font
#zh_font = matplotlib.font_manager.FontProperties(fname='wqy-microhei')
#s=u'\u54c8\u54c8' #Need the unicode for your Chinese Char.
fontP = font_manager.FontProperties()
fontP.set_family('WenQuanYi Zen Hei')
fontP.set_size(14)
# plt.text(0.5,0.5,s,fontproperties=fontP, size=50) #example: plt.text()

# start graph
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'), figsize=(20, 10))

scatter = ax.scatter(df.tweets,
                     df.conversation,
                     s=df["tweets"] / 50,
                     c=df.conversation,
                     alpha=0.5,
                     cmap=plt.cm.jet)

ax.set_title("Hashtags distribution per tweet and conversation", size=20)

labels = ['point {0}'.format(i + 1) for i in range(len(df))]
# labels=df.label.values.tolist()

fig.plugins = [plugins.PointLabelTooltip(scatter, labels)]

# <codecell>

# <codecell>
Пример #14
0
    def wholeday(self):
        self.loadAlldata()

        # fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
        fig = plt.figure(figsize=(8, 24))  # 8 inches wide by 6 inches tall
        ax1 = fig.add_subplot(4, 1, 1)
        ax2 = fig.add_subplot(4, 1, 2)
        ax3 = fig.add_subplot(4, 1, 3)
        ax4 = fig.add_subplot(4, 1, 4)
        c = np.array([int(x) for x in self.daylog.keys()])
        # print(c)
        P = range(len(c))
        A = np.array(list(self.daylog.values()))[:, -1]
        # fig, ax = plt.subplots()
        points = ax1.scatter(P, A, c=A, s=100, alpha=0.5)
        labels = ["login time: {0}".format(i) for i in A]
        # print(labels)
        ax1.set_title("whole log in time")
        # ax1.set_xlabel("days")
        ax1.set_ylabel("hours")

        if len(self.desk) < 1:
            self.loadAlldata()
        print(self.desk.values())
        activity = self.desk
        # for k in list(activity.keys()):
        #     plt.hist( activity[k],list(activity.keys()), stacked=True)
        # plt.show()
        c = []
        v0 = []
        v1 = []
        v2 = []
        v3 = []
        v4 = []
        for key, val in activity.items():
            c.append(key)
            v0.append(val[0])
            v1.append(val[1])
            v2.append(val[2])
            v3.append(val[3])
            v4.append(val[4])
        v0 = np.array(v0)
        v1 = np.array(v1)
        v2 = np.array(v2)
        v3 = np.array(v3)
        v4 = np.array(v4)
        # print(v0)
        # print(v1)
        # print(v2)
        p0 = ax2.bar(range(len(c)), v4, linewidth=3)
        p1 = ax2.bar(range(len(c)), v3, bottom=v4, linewidth=3)
        p2 = ax2.bar(range(len(c)), v2, bottom=v4 + v3, linewidth=3)
        p3 = ax2.bar(range(len(c)), v1, bottom=v4 + v3 + v2, linewidth=3)
        p4 = ax2.bar(range(len(c)), v0, bottom=v4 + v1 + v2 + v3, linewidth=3)
        # ax2.xticks(range(len(c)), c)
        ax2.legend((p4[0], p3[0], p2[0], p1[0], p0[0]),
                   ('very not productive', 'not productive', 'neutural',
                    'productive', 'very productive'),
                   loc=1)
        # ax2.set_xlabel("days")
        ax2.set_ylabel("hours")
        ax2.set_title("productivity for days in a month")
        # ax2.set_xticks(np.arange(0, 30, 2), np.arange(0, 30, 2))
        # plt.title("sleep pattern for days in a month")
        ax2.set_xlim(-0.5, 30)
        ax2.set_ylim(0, 24)

        tooltip = plugins.PointLabelTooltip(points, labels)

        plugins.connect(fig, tooltip)

        activity = self.activity
        # lines = open(file, 'r').readlines()
        # for i in range(1, len(lines)):
        #     tokes = lines[i].strip().split(',')
        #     activity[i] = [float(t)/60 for t in tokes]
        #     # print(activity[i])
        # print( activity.values(),list(activity.keys()))
        # for k in list(activity.keys()):
        #     plt.hist( activity[k],list(activity.keys()), stacked=True)
        # plt.show()
        c = []

        v0 = []
        v1 = []
        v2 = []
        for key, val in activity.items():
            c.append(key)
            v0.append(val[0] / 60)
            v1.append(val[1] / 60)
            v2.append(val[2] / 60)
        v0 = np.array(v0)
        v1 = np.array(v1)
        v2 = np.array(v2)
        # print(v0)
        # print(v1)
        # print(v2)
        p0 = ax3.bar(range(len(c)), v0, linewidth=1.5)
        p1 = ax3.bar(range(len(c)), v1, bottom=v0, linewidth=1.5)
        p2 = ax3.bar(range(len(c)), v2, bottom=v1 + v0, linewidth=1.5)
        ax3.set_xticks(range(len(c)), c)
        ax3.legend((p0[0], p1[0], p2[0]),
                   ('Lightly Active', 'Fairly Active', 'Very Active'))
        ax3.set_xlabel("days")
        ax3.set_ylabel("hours")
        ax3.set_title("level of activity")
        # ax3.set_xticks(np.arange(0, 30, 2), np.arange(0, 30, 2))
        # plt.title("sleep pattern for days in a month")
        ax3.set_xlim(-0.5, 30)
        ax3.set_ylim(0, 24)

        activity = self.sleep
        # for k in list(activity.keys()):
        #     plt.hist( activity[k],list(activity.keys()), stacked=True)
        # plt.show()
        c = []
        v0 = []
        v1 = []
        v2 = []
        v3 = []
        for key, val in activity.items():
            c.append(key)
            v0.append(val[0] / 60)
            v1.append(val[1] / 60)
            v2.append(val[2] / 60)
            v3.append(val[3] / 60)
        v0 = np.array(v0)
        v1 = np.array(v1)
        v2 = np.array(v2)
        v3 = np.array(v3)
        # print(v0)
        # print(v1)
        # print(v2)
        p3 = ax4.bar(range(len(c)), v3, linewidth=3)
        p2 = ax4.bar(range(len(c)), v2, bottom=v3, linewidth=3)
        p1 = ax4.bar(range(len(c)), v1, bottom=v3 + v2, linewidth=3)
        p0 = ax4.bar(range(len(c)), v0, bottom=v2 + v1 + v3, linewidth=3)
        # ax4.xticks(range(len(c)), c)
        ax4.legend((p0[0], p1[0], p2[0], p3[0]),
                   ('awake', 'REM', 'light sleep', 'deep sleep'))
        ax4.set_xlabel("days")
        ax4.set_ylabel("hours")
        ax4.set_title("sleep pattern for days in a month")
        # ax4.xticks(np.arange(0, 30, 2), np.arange(0, 30, 2))
        # plt.title("sleep pattern for days in a month")
        ax4.set_xlim(-0.5, 30)
        ax4.set_ylim(0, 24)

        # mpld3.show()
        mpld3.save_html(fig, "wholeday.html")
Пример #15
0
ax.scatter(x, y, c=color, s=size, alpha=0.3)

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_title('Matplotlib Plot Rendered in D3!', size=14)

ax.grid(color='lightgray', alpha=0.7)

# <codecell>

fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100

scatter = ax.scatter(np.random.normal(size=N),
                     np.random.normal(size=N),
                     c=np.random.random(size=N),
                     s = 1000 * np.random.random(size=N),
                     alpha=0.3,
                     cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')

ax.set_title("Scatter Plot (with tooltips!)", size=20)

labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = plugins.PointLabelTooltip(scatter, labels=labels)
plugins.connect(fig, tooltip)

# <codecell>