def makeRasterChart(
    results,
    point_results=None,
    basename=None,
    type="svg",
    labels=("Cross-section of Transect ", "Distance", "Elevation"),
):
    import pylab as p

    for t in results.keys():
        p.figure(figsize=(17, 8.5))
        p.plot(results[t][0], results[t][1])
        if point_results and len(point_results[t][0]) > 1:
            p.scatter(point_results[t][0], point_results[t][1])
            for z in zip(point_results[t][0], point_results[t][1], point_results[t][2]):
                p.annotate("   " + z[2], (z[0], z[1]), ha="center", va="bottom", rotation="vertical", size=8)
        p.xlabel(labels[1])
        p.ylabel(labels[2])
        p.title(labels[0] + t)
        p.xlim(0, max(results[t][0]))
        p.grid(True)
        if basename:
            p.savefig(basename + t + "." + type)
            p.close()
        else:
            p.show()
    def _plot(self, fits_params, tau, tsys, r2, sec_el, fit, hot_sky, path):
        """
        図の出力、保存
        """
        fig = pylab.figure()
        pylab.grid()
        pylab.ylabel("log((Phot-Psky)/Phot)")
        pylab.xlabel("secZ")

        pylab.plot(sec_el, hot_sky, "o", markersize=7)
        pylab.plot(sec_el, fit)
        pylab.annotate(
            "tau = %.2f, Tsys* = %.2f, R^2 = %.3f" % (tau, tsys, r2),
            xy=(0.6, 0.9),
            xycoords="axes fraction",
            size="small",
        )

        # if (fits_params[0]["BACKEND"])[-1]=="1" : direction="H"
        # elif (fits_params[0]["BACKEND"])[-1]=="2" : direction="V"
        # else : pass
        # figure_name = str(fits_params[0]["MOLECULE"])+direction+".png"
        figure_name = str(fits_params[0]["MOLECULE"]) + ".png"
        # file_manager.mkdir(path)
        pylab.savefig(path + figure_name)
        # file_manager.mkdir('/home/1.85m/data/Qlook/skydip/' + path.split('/')[-1])
        # pylab.savefig('/home/1.85m/data/Qlook/skydip/'+ path.split('/')[-1] + '/' + figure_name)

        """ 
Example #3
0
def PlotNumberOfTags(corpus):
    word_tag_dict = defaultdict(set)

    for (word, tag) in corpus:
        word_tag_dict[word].add(tag)
    # using Counter for efficiency (leaner than FreqDist)
    C = Counter(len(val) for val in word_tag_dict.itervalues())

    pylab.subplot(211)
    pylab.plot(C.keys(), C.values(), "-go", label="Linear Scale")
    pylab.suptitle("Word Ambiguity:")
    pylab.title("Number of Words by Possible Tag Number")
    pylab.box("off")  # for better appearance
    pylab.grid("on")  # for better appearance
    pylab.ylabel("Words With This Number of Tags (Linear)")
    pylab.legend(loc=0)
    # add value tags
    for x, y in zip(C.keys(), C.values()):
        pylab.annotate(str(y), (x, y + 0.5))

    pylab.subplot(212)
    pylab.plot(C.keys(), C.values(), "-bo", label="Logarithmic Scale")
    pylab.yscale("log")  # to make the graph more readable, for the log graph version
    pylab.box("off")  # for better appearance
    pylab.grid("on")  # for better appearance
    pylab.xlabel("Number of Tags per Word")
    pylab.ylabel("Words With This Number of Tags (Log)")
    pylab.legend(loc=0)
    # add value tags
    for x, y in zip(C.keys(), C.values()):
        pylab.annotate(str(y), (x, y + 0.5))

    pylab.show()
def plot_pulling_force(times, pulling_forces, normal_force, info_for_naming="", show=True):
    pulling_forces = np.array(pulling_forces)  # may be redundant
    fx_max, time_of_fx_max, fx_max_ix = get_pulling_force_max_and_meta(times, pulling_forces, normal_force=normal_force)
    defaults = {"markersize": 1, "linewidth": 0.1}
    fig = pl.figure()
    for ix_dim, name in zip(range(len(pulling_forces[0])), ["Fx"]):  # , 'Fy', 'Fz']):
        pl.plot(times, pulling_forces[:, ix_dim], "o-", label=name, **defaults)
    pl.ylabel("Fp")
    pl.xlabel("Time")
    pl.title("Pulling force vs time")
    # Max Fx:
    pl.annotate(
        "$F_x={:.1f}$".format(fx_max),
        xy=(time_of_fx_max, fx_max),
        xytext=(0.2, 0.9),
        textcoords="axes fraction",
        fontsize=14,
        arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-0.1"),
    )
    # Sim info:
    pl.ylim(ymin=-2)  # make room for it
    pl.annotate(info_for_naming, xy=(0.01, 0.03), xycoords="axes fraction", fontsize=12)
    pl.savefig("{}/plots/svg/Fp {}.svg".format(working_directory, info_for_naming))
    pl.savefig("{}/plots/Fp {}.png".format(working_directory, info_for_naming))
    if show:
        pl.show()
    else:
        pl.close()
Example #5
0
def bfAnnotate(xRange, yVals, M, fig, scale):
    counter = 1  # used for annotating
    for d in range(xRange):  # only if BF is true
        for date in M.getTrends():
            # Annotations
            if date.day == d % 365 and counter == 1:
                pylab.annotate(
                    date.name,
                    xy=(d, yVals[d]),
                    textcoords="offset points",
                    xytext=(0, scale * yVals[d]),
                    ha="center",
                    arrowprops=dict(arrowstyle="->", connectionstyle="arc"),
                )
                counter += 1
                counter %= 2
            elif date.day == d % 365 and counter == 0:
                pylab.annotate(
                    date.name,
                    xy=(d, yVals[d]),
                    textcoords="offset points",
                    xytext=(0, -scale * yVals[d]),
                    ha="center",
                    arrowprops=dict(arrowstyle="->", connectionstyle="arc"),
                )
                counter += 1
                counter %= 2
Example #6
0
def annotator(data, labels, lang):
    labelStyle = "normal" if lang == "en" else "italic"
    color = "blue" if lang == "en" else "red"
    for label, x, y in zip(labels, data[:, 0], data[:, 1]):
        if label in ["man", "hombre", "woman", "mujer"]:
            pylab.scatter([x], [y], 20, [color])
            pylab.annotate(label, xy=(x, y), style=labelStyle)
Example #7
0
def demo():
    """
    Show the available interface functions and the corresponding probability
    density functions.
    """

    # Plot the cdf and pdf
    import pylab

    w = 10
    perf = Erf(w)
    ptanh = Tanh(w)
    plinear = Linear(2.35 * w)

    # arrowprops=dict(arrowstyle='wedge',connectionstyle='arc3',fc='0.6')
    # bbox=dict(boxstyle='round', fc='0.8')

    z = pylab.linspace(-3 * w, 3 * w, 800)
    pylab.subplot(211)
    pylab.plot(z, perf.cdf(z), hold=False)
    pylab.plot(z, ptanh.cdf(z), hold=True)
    pylab.plot(z, plinear.cdf(z), hold=True)
    pylab.axvline(w, linewidth=2)
    pylab.annotate("1-sigma", xy=(w * 1.1, 0.2))
    pylab.legend(["erf", "tanh"])
    pylab.grid(True)
    pylab.subplot(212)
    pylab.plot(z, perf.pdf(z), hold=False)
    pylab.plot(z, ptanh.pdf(z), hold=True)
    pylab.plot(z, plinear.pdf(z), hold=True)
    pylab.axvline(w, linewidth=2)
    pylab.annotate("1-sigma", xy=(w * 1.1, 0.2))
    pylab.legend(["erf", "tanh", "linear"])
    pylab.grid(True)
def appmagplot(lbound, thetalist):
    count = 0
    for i in range(0, 25):
        if thetalist[4][i] < lbound:
            count = count + 1
            p.scatter(thetalist[3][i], thetalist[4][i])
            p.annotate(
                thetalist[0][i + 1][0:3],
                xy=(thetalist[3][i], thetalist[4][i]),
                xytext=(thetalist[3][i] - 1, thetalist[4][i] + 0.5 * random.choice([-1, 1])),
                arrowprops=None,
            )
        else:
            p.scatter(thetalist[3][i], thetalist[4][i], marker="^", c="r")
            p.annotate(
                thetalist[0][i + 1][0:3],
                xy=(thetalist[3][i], thetalist[4][i]),
                xytext=(thetalist[3][i] - 1, thetalist[4][i] + 0.5 * random.choice([-1, 1])),
                arrowprops=None,
            )

    p.title("Satellites with an Apparent Magnitude Brighter Than " + str(lbound) + " (" + str(count) + ")")
    p.xlabel("Radius (arcminutes)")
    p.ylabel("Apparent Magnitude")
    p.text(-4.9, lbound, "Apparent Magnitude Cutoff", weight="bold")
    p.axhline(y=lbound)
    p.gca().invert_yaxis()
    p.show()
Example #9
0
def plotVec2(antList=[1, 2, 3, 4, 5, 6]):
    color = ["b", "g", "r", "c", "m", "y", "b", "g", "r", "c", "m", "y", "b", "g", "r"]
    pbCorrectedVis = numpy.load("lastVis.npy")
    tsys = numpy.load("lastTsys.npy")
    snrMatrix = pbcorrectedVis * tsysMatrix * KperJyMatrix
    # element-wise multiplication of elements
    vecList = numpy.zeros([15, 17], dtype=complex)
    # ... list of (x,y) values, as complex numbers, for each vector, beginning with (0,0)
    maxScalarSum = 0.0
    pylab.ion()
    pylab.clf()
    for n in range(0, 15):
        scalarSum = 0.0
        for m in range(0, 16):
            if numpy.isnan(numpy.real(pbCorrectedVis[m][n])) or numpy.isnan(numpy.imag(pbCorrectedVis[m][n])):
                vecList[n][m + 1] = vecList[n][m]  # if nan, repeat last value
            else:
                vecList[n][m + 1] = vecList[n][m] + pbCorrectedVis[m][n]
                scalarSum += numpy.abs(pbCorrectedVis[m][n])
        if scalarSum > maxScalarSum:
            maxScalarSum = scalarSum
        print "\nvecList for ant %d:" % (n + 1)
        print numpy.array_str(vecList[n], precision=2, max_line_width=200)
    pylab.axis([-1.05 * maxScalarSum, 1.05 * maxScalarSum, -1.05 * maxScalarSum, 1.05 * maxScalarSum])
    for n in range(0, 15):
        x = numpy.real(vecList[n])
        y = numpy.imag(vecList[n])
        color = "m"
        if (n + 1) in antList:
            color = "r"
        pylab.plot(x, y, color=color, linestyle="solid", linewidth=4)
        pylab.annotate(str(n + 1), [x[15], y[15]])
    pylab.grid(True)
    pylab.axes().set_aspect("equal")
    pylab.draw()
def plot_mixtures_vs_K(model):
    prefix = "mixtures_vs_K_%s" % model
    plt.figure(figsize=(5, 5))
    plt.clf()
    for K in Ks:
        pars = get_pars(model, K)
        amps = pars[0:K]
        sigmas = np.sqrt(pars[K : 2 * K])
        plt.plot(sigmas, amps, "k-", alpha=0.5)
        plt.plot(sigmas, amps, "ko", ms=3.0)
        label = r"%d" % K
        tweak = 0.0
        if model == "dev" or model == "luv":
            tweak = 4
            if K == 10:
                tweak = -2
        if model == "lux":
            tweak = 4 * (7 - K)
        plt.annotate(
            label, [sigmas[0], amps[0]], xytext=[-4, -4], textcoords="offset points", va="baseline", ha="right"
        )
        plt.annotate(
            label, [sigmas[-1], amps[-1]], xytext=[4, -4 + tweak], textcoords="offset points", va="baseline", ha="left"
        )
    plt.xlabel(r"root-variance $\sqrt{v^{\mathrm{%s}}_m}$ (units of half-light radii)" % model)
    plt.ylabel(r"amplitudes $c^{\mathrm{%s}}_m$" % model)
    plt.title(r"approximations to %s" % model)
    plt.loglog()
    plt.xlim(0.5e-4, 2.0e1)
    plt.ylim(0.5e-4, 2.0e1)
    hogg_savefig(prefix + ".png")
    hogg_savefig(prefix + ".pdf")
    return None
Example #11
0
File: model.py Project: kdz/pystemm
def graph_file(obj, func_name, param, range, highlights):
    ## plots the named function on obj, taking param over its range (start, end)
    ## highlights are pairs of (x_value, "Text_to_show") to annotate on the graph plot
    ## saves the plot to a file and returns full file name

    import numpy, pylab

    func = getattr(obj, func_name)
    f = numpy.vectorize(func)
    x = numpy.linspace(*range)
    y = f(x)
    pylab.rc("font", family="serif", size=20)
    pylab.plot(x, y)
    pylab.xlabel(param)
    pylab.ylabel(func_name)
    hi_pts = [pt for pt, txt in highlights]
    pylab.plot(hi_pts, f(hi_pts), "rD")
    for pt, txt in highlights:
        pt_y = func(pt)
        ann = txt + "\n(%s,%s)" % (pt, pt_y)
        pylab.annotate(ann, xy=(pt, pt_y))

    import os, time

    file = os.path.dirname(__file__) + "/generated_graphs/%s.%s.%s.pdf" % (type(obj).__name__, func_name, time.time())
    pylab.savefig(file, dpi=300)
    pylab.close()
    return file
def plot_mixtures_vs_model(K):
    prefix = "mixtures_vs_model_K%02d" % K
    plt.figure(figsize=(5, 5))
    plt.clf()
    for model in models[0:5]:
        pars = get_pars(model, K)
        amps = pars[0:K]
        sigmas = np.sqrt(pars[K : 2 * K])
        plt.plot(sigmas, amps, "k-", alpha=0.5)
        plt.plot(sigmas, amps, "ko", ms=3.0)
        label = model
        tweak = 0.0
        if model == "ser5":
            tweak = 5.0
        if model == "dev":
            tweak = 1.0
        plt.annotate(
            label, [sigmas[0], amps[0]], xytext=[-2, -10], textcoords="offset points", va="baseline", ha="center"
        )
        plt.annotate(
            label, [sigmas[-1], amps[-1]], xytext=[4, -4 + tweak], textcoords="offset points", va="baseline", ha="left"
        )
    model = "ser"
    plt.xlabel(r"root-variance $\sqrt{v^{\mathrm{%s}}_m}$ (units of half-light radii)" % model)
    plt.ylabel(r"amplitudes $c^{\mathrm{%s}}_m$" % model)
    plt.title(r"approximations to ser profiles at $M^{\mathrm{ser}}=%d$" % K)
    plt.loglog()
    plt.xlim(0.5e-4, 2.0e1)
    plt.ylim(0.5e-4, 2.0e1)
    hogg_savefig(prefix + ".png")
    hogg_savefig(prefix + ".pdf")
    return None
Example #13
0
 def plot(self):
     """ Plot the positions of the fibers for this IFU """
     points = np.array([(v[0], v[1], k, i) for (k, v), i in zip(self.offsets.items(), self.ifu) if v is not None])
     plt.plot(points[:, 0], points[:, 1], "x")
     for x, y, label, ifu in points:
         plt.annotate(int(label), xy=(x, y), xytext=(0, (ifu - 1) * 10), textcoords="offset points")
     plt.show()
Example #14
0
def construct_gs_hist(del_bl=8.0, num_bl=10, beam_sig=0.09, fq=0.1):
    save_tag = "grid_del_bl_{0:.2f}_num_bl_{1}_beam_sig_{2:.2f}_fq_{3:.3f}".format(del_bl, num_bl, beam_sig, fq)
    save_tag_mc = "grid_del_bl_{0:.2f}_num_bl_{1}_beam_sig_{2:.2f}_fq_{3}".format(del_bl, num_bl, beam_sig, fq)
    ys = load_mc_data("{0}/monte_carlo/{1}".format(data_loc, save_tag_mc))
    print "ys ", ys.shape

    alms_fg = qgea.generate_sky_model_alms(gsm_fits_file, lmax=3)
    alms_fg = alms_fg[:, 2]

    baselines, Q, lms = load_Q_file(gh="grid", del_bl=del_bl, num_bl=num_bl, beam_sig=beam_sig, fq=fq, lmax=3)
    N = total_noise_covar(0.1, baselines.shape[0], "{0}/gsm_matrices/gsm_{1}.npz".format(data_loc, save_tag))
    MQN = return_MQdagNinv(Q, N, num_remov=None)
    print MQN
    ahat00s = n.array([])
    for ii in xrange(ys.shape[1]):
        # _,ahat,_ = qgea.test_recover_alms(ys[:,ii],Q,N,alms_fg,num_remov=None)
        ahat = uf.vdot(MQN, ys[:, ii])
        ahat00s = n.append(n.real(ahat[0]), ahat00s)
    # print ahat00s
    print ahat00s.shape
    _, bins, _ = p.hist(ahat00s, bins=36, normed=True)

    # plot best fit line
    mu, sigma = norm.fit(ahat00s)
    print "mu, sigma = ", mu, ", ", sigma
    y_fit = mpl.mlab.normpdf(bins, mu, sigma)
    p.plot(bins, y_fit, "r--", linewidth=2)

    p.xlabel("ahat_00")
    p.ylabel("Probability")
    p.title(save_tag)
    p.annotate("mu = {0:.2f}\nsigma = {1:.2f}".format(mu, sigma), xy=(0.05, 0.5), xycoords="axes fraction")
    p.savefig("./figures/monte_carlo/{0}.pdf".format(save_tag))
    p.clf()
Example #15
0
def plotScoringFunction(data, bestParameterSet, patients, scoringFunction):
    x = []
    y = []
    labels = []
    for i in range(data.shape[1]):
        if (
            abs((data[:, i][0]) - (bestParameterSet[0])) < 0.00001
            and abs((data[:, i][2]) - (bestParameterSet[2])) < 0.00001
            and abs((data[:, i][1]) - (bestParameterSet[1])) < 0.00001
            and abs((data[:, i][3]) - (bestParameterSet[3])) < 0.00001
            and abs((data[:, i][4]) - (bestParameterSet[4])) < 0.00001
        ):
            x += [data[:, i][5]]
            y += [data[:, i][6]]
            labels += [patients[i]]

    scoringFunction(x, y, plot=True)
    for label, xi, yi in zip(labels, x, y):
        plt.annotate(
            label,
            xy=(xi, yi),
            textcoords="offset points",
            ha="right",
            va="bottom",
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
        )
def plot3(x, y, z, cols):
    fig = plt.figure(1, figsize=(4, 3))
    plt.clf()

    ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)
    plt.cla()

    ax.scatter(x, y, z, c=cols.astype(np.float), s=100)
    ax.w_xaxis.set_ticklabels([])
    ax.w_yaxis.set_ticklabels([])
    ax.w_zaxis.set_ticklabels([])
    ax.set_xlabel("1st Component")
    ax.set_ylabel("2nd Component")
    ax.set_zlabel("3rd Component")

    for i in range(0, nAksharas, nAksharas // 100):
        akshara, count = aksh_counts[i]
        if count < threshold:
            continue
        x2, y2, _ = proj3d.proj_transform(x[i], y[i], z[i], ax.get_proj())
        pylab.annotate(
            akshara,
            xycoords="data",
            xy=(x2, y2),
            xytext=(60, 20),
            textcoords="offset points",
            ha="right",
            va="bottom",
            bbox=dict(boxstyle="round,pad=0.5", fc="yellow", alpha=0.5),
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
        )
    plt.show()
Example #17
0
def stringtest():

    import Levenshtein

    strings = [
        "King Crimson",
        "King Lear",
        "Denis Leary",
        "George Bush",
        "George W. Bush",
        "Barack Hussein Obama",
        "Saddam Hussein",
        "George Leary",
    ]

    dist = distmatrix(strings, c=lambda x, y: 1 - Levenshtein.ratio(x, y))

    p = fastmap(dist, 2)
    import pylab

    pylab.scatter([x[0] for x in p], [x[1] for x in p], c="r")
    for i, s in enumerate(strings):
        pylab.annotate(s, p[i])

    pylab.title("Levenshtein distance mapped to 2D coordinates")
    pylab.savefig("strings.png")
Example #18
0
def plot_embedding(data_matrix, y, labels=None, image_file_name=None, title=None, cmap="rainbow", density=False):
    """plot_embedding."""
    import matplotlib.pyplot as plt
    from matplotlib import offsetbox
    from PIL import Image
    from eden.embedding import embed_dat_matrix_two_dimensions

    if title is not None:
        plt.title(title)
    if density:
        embed_dat_matrix_two_dimensions(data_matrix, y=y, instance_colormap=cmap)
    else:
        plt.scatter(data_matrix[:, 0], data_matrix[:, 1], c=y, cmap=cmap, alpha=0.7, s=30, edgecolors="black")
        plt.xticks([])
        plt.yticks([])
        plt.axis("off")
    if image_file_name is not None:
        num_instances = data_matrix.shape[0]
        ax = plt.subplot(111)
        for i in range(num_instances):
            img = Image.open(image_file_name + str(i) + ".png")
            imagebox = offsetbox.AnnotationBbox(
                offsetbox.OffsetImage(img, zoom=1), data_matrix[i], pad=0, frameon=False
            )
            ax.add_artist(imagebox)
    if labels is not None:
        for id in range(data_matrix.shape[0]):
            label = str(labels[id])
            x = data_matrix[id, 0]
            y = data_matrix[id, 1]
            plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords="offset points")
Example #19
0
def plot_color(A, filename, ticklabels=None, annotate=True):
    nregion1 = A.shape[0]
    nregion2 = A.shape[1]
    P.clf()

    cdict = {
        "red": ((0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.4, 0.4)),
        "green": ((0.0, 0.4, 0.4), (0.5, 1.0, 1.0), (1.0, 0.4, 0.4)),
        "blue": ((0.0, 0.4, 0.4), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)),
    }
    my_cmap = matplotlib.colors.LinearSegmentedColormap("my_colormap", cdict, 256)
    vmax = np.max(A * 100)
    vmin = np.min(A * 100)
    vmax = max(-vmin, vmax)
    vmin = min(-vmax, vmin)
    # print vmax,vmin
    #  P.pcolor(A*100,cmap=my_cmap,edgecolors='k',vmin=vmin,vmax=vmax,array=True)
    P.imshow(A * 100, cmap=my_cmap, vmin=vmin, vmax=vmax, interpolation="nearest", origin="upper")

    thresh = 0.05 * (vmax - vmin)

    if annotate:
        for r1 in range(0, nregion1):
            for r2 in range(0, nregion2):
                n = A[r1, r2] * 100
                if abs(n) > thresh:
                    P.annotate("%.1f" % (n), (r2, r1), ha="center", va="center", fontsize=2)
    a = P.gca()
    a.get_xaxis().tick_top()
    for i in ["top", "right", "left", "bottom"]:
        a.spines[i].set_visible(False)
    a.tick_params(labelsize=10, width=0)
    P.savefig(filename)
Example #20
0
    def tag_article_tsne_plot(self, sample_size=20000):
        samples = numpy.random.randint(0, 1000000, sample_size)
        self.combined_matrix = numpy.concatenate((self.doc_vec[samples,], self.tag_vec), axis=0)
        self.combined_2d = bh_sne(self.combined_matrix)

        font = {"fontname": "Tahoma", "fontsize": 0.1, "verticalalignment": "top", "horizontalalignment": "center"}
        pylab.subplots_adjust(bottom=0.1)
        pylab.scatter(
            self.combined_2d[: sample_size + 1, 0],
            self.combined_2d[: sample_size + 1, 1],
            marker=".",
            cmap=pylab.get_cmap("Spectral"),
        )
        pylab.scatter(
            self.combined_2d[sample_size + 1 :, 0],
            self.combined_2d[sample_size + 1 :, 1],
            marker="x",
            cmap=pylab.get_cmap("Spectral"),
        )
        pylab.title("NYT Articles and Labels(1991-2007)")
        pylab.xlabel("X")
        pylab.ylabel("Y")
        for label, x, y in zip(
            self.tags, self.combined_2d[sample_size + 1 :, 0], self.combined_2d[sample_size + 1 :, 1]
        ):
            pylab.annotate(label, xy=(x, y), xytext=None, ha="right", va="bottom", **font)
            # ,textcoords = 'offset points',bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
            # arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

        pylab.savefig(
            "/mnt/data/tag_article_plot", bbox_inches="tight", dpi=1000, orientation="landscape", papertype="a0"
        )
        pylab.close()
Example #21
0
def plot_words(wordVectors, set1p, set1n, imgFile):

    X = []
    labels = []
    for word in set1p + set1n:
        if word in wordVectors:
            labels.append(word)
            X.append(wordVectors[word])

    X = numpy.array(X)
    for r, row in enumerate(X):
        X[r] /= math.sqrt((X[r] ** 2).sum() + 1e-6)

    Y = tsne(X, 2, 80, 20.0)
    Plot.scatter(Y[:, 0], Y[:, 1], s=0.1)
    for label, x, y in zip(labels, Y[:, 0], Y[:, 1]):
        if label in set1p:
            Plot.annotate(
                label, color="green", xy=(x, y), xytext=None, textcoords=None, bbox=None, arrowprops=None, size=10
            )
        if label in set1n:
            Plot.annotate(
                label, color="red", xy=(x, y), xytext=None, textcoords=None, bbox=None, arrowprops=None, size=10
            )

    Plot.savefig(imgFile, bbox_inches="tight")
    Plot.close()
Example #22
0
    def show_neighboor(self):
        import pylab

        nghx = []
        nghy = []

        for i in range(self.keypoints.x.size):
            y, x = self.nearest_peak((self.keypoints.y[i], self.keypoints.x[i]))
            nghx.append(x)
            nghy.append(y)

        nghx = numpy.asarray(nghx)
        nghy = numpy.asarray(nghy)

        pylab.figure()
        pylab.imshow(self.raw, interpolation="nearest")
        pylab.plot(self.keypoints.x, self.keypoints.y, "og")

        for i in range(self.keypoints.x.size):
            pylab.annotate(
                "",
                xy=(nghx[i], nghy[i]),
                xytext=(self.keypoints.x[i], self.keypoints.y[i]),
                arrowprops=dict(facecolor="red", shrink=0.05),
            )
Example #23
0
def createPlot(dataY, dataX, ticksX, annotations, axisY, axisX, dostep, doannotate):
    if not ticksX:
        ticksX = dataX

    if dostep:
        py.step(dataX, dataY, where="post", linestyle="-", label=axisY)  # where=post steps after point
    else:
        py.plot(dataX, dataY, marker="o", ms=5.0, linestyle="-", label=axisY)

    if annotations and doannotate:
        for note, x, y in zip(annotations, dataX, dataY):
            py.annotate(note, (x, y), xytext=(2, 2), xycoords="data", textcoords="offset points")

    py.xticks(np.arange(1, len(dataX) + 1), ticksX, horizontalalignment="left", rotation=30)
    leg = py.legend()
    leg.draggable()
    py.xlabel(axisX)
    py.ylabel("time (s)")

    # Set X axis tick labels as rungs
    # print zip(dataX, dataY)

    py.draw()
    py.show()

    return
Example #24
0
def plot_dens(x, y, filename, point):                   

    majorLocator   = MultipleLocator(1)
    majorFormatter = FormatStrFormatter('%d')
    minorLocator   = MultipleLocator(0.2)
  
#    fig = pl.figure()   
    fig, ax = plt.subplots()                        
    pl.plot(x, y, 'b-', x, y, 'k.')
    fig.suptitle(filename)
    # pl.plot(z, R, 'k.')
    #fig.set_xlim(0,4.0)
    #fig.set_ylim(0,3)                
    # fig = plt.gcf()
    plt.xticks(ticki)
#    plt.xticks(range(0,d_max_y,50))
    pl.xlim(0,12)
    pl.ylim(0,max(y))
    pl.xlabel('z [nm]')
    pl.ylabel('Density [kg/nm3]')
#    pl.grid(b=True, which='both', axis='both', color='r', linestyle='-', linewidth=0.5)
    # fig.set_size_inches(18.5,10.5)
    pl.annotate('first peak', xy=(point[0], point[1]),  xycoords='data', xytext=(-50, 30), textcoords='offset points', arrowprops=dict(arrowstyle="->"))

    ax.xaxis.set_major_locator(majorLocator)
    ax.xaxis.set_major_formatter(majorFormatter)

    #for the minor ticks, use no labels; default NullFormatter
    ax.xaxis.set_minor_locator(minorLocator)

    ax.xaxis.grid(True, which='minor')
    ax.yaxis.grid(True, which='major')

    return fig
Example #25
0
 def plotChromBorders(self, chromOffset):
     min_y, max_y = plt.ylim()
     ypos = max_y - (max_y - min_y) * 0.1
     for k, v in chromOffset.iteritems():
         plt.plot([v, v], [min_y, max_y], "k-.", lw=1)
         if k != chromOffset.index.max():
             plt.annotate("CH{}".format(k), xy=(v, ypos))
     plt.xticks(chromOffset.values)
    def give_plot():
        pl.figure()

        pl.plot(self.df[self.action_col], "o-", color="blue")
        count = 1
        for ele, unique_id in zip(self.df.index, self.df[self.action_col]):
            pl.annotate(str(ele), xy=(count, unique_id), xytext=(count, unique_id + 5), ha="right")
            count = count + 1
        pl.show()
Example #27
0
def plotSamples(samples, marker):
    xVals, yVals = [], []
    for s in samples:
        x = s.getFeatures()[0]
        y = s.getFeatures()[1]
        pylab.annotate(s.getName(), xy=(x, y), xytext=(x + 0.13, y - 0.07), fontsize="x-large")
        xVals.append(x)
        yVals.append(y)
    pylab.plot(xVals, yVals, marker)
Example #28
0
def plotHighAndLowTemps(lowTemps, highTemps):
    pylab.figure(2)
    pylab.plot(range(1, 32), lowTemps, "b--")
    pylab.plot(range(1, 32), highTemps, "r-")
    pylab.title("Day by Day High and Low Temperatures in Boston in July 2012")
    pylab.xlabel("Days")
    pylab.ylabel("Temperature")
    pylab.annotate("High", (31.5, highTemps[-1]), color="r")
    pylab.annotate("Low", (31.5, lowTemps[-1]), color="b")
    pylab.show()
Example #29
0
def plot6Subplots(scoredData, data, bestParameterSet, patients):
    plt.figure()
    # first five
    for j in range(5):
        x = []
        y = []
        for i in range(scoredData.shape[1]):
            if (
                abs((scoredData[:, i][(j + 1) % 5]) - (bestParameterSet[(j + 1) % 5])) < 0.00001
                and abs((scoredData[:, i][(j + 2) % 5]) - (bestParameterSet[(j + 2) % 5])) < 0.00001
                and abs((scoredData[:, i][(j + 3) % 5]) - (bestParameterSet[(j + 3) % 5])) < 0.00001
                and abs((scoredData[:, i][(j + 4) % 5]) - (bestParameterSet[(j + 4) % 5])) < 0.00001
            ):
                x += [scoredData[:, i][j]]
                y += [scoredData[:, i][5]]
        plt.subplot(3, 2, j + 1)
        plt.plot(x, y, "bo")
        plt.axvline(x=bestParameterSet[j])
        plt.title(parameterList[j])

    # last
    x = []
    y = []
    labels = []
    for i in range(data.shape[1]):
        if (
            abs((data[:, i][0]) - (bestParameterSet[0])) < 0.00001
            and abs((data[:, i][2]) - (bestParameterSet[2])) < 0.00001
            and abs((data[:, i][1]) - (bestParameterSet[1])) < 0.00001
            and abs((data[:, i][3]) - (bestParameterSet[3])) < 0.00001
            and abs((data[:, i][4]) - (bestParameterSet[4])) < 0.00001
        ):
            x += [data[:, i][5]]
            y += [data[:, i][6]]
            labels += [patients[i]]

    x = np.array(x)
    y = np.array(y)
    plt.subplot(3, 2, 6)
    fit = np.polyfit(x, y, 1)
    line = np.poly1d(fit)
    plt.plot(x, y, "bo")
    plt.plot(x, line(x), "--c")
    plt.plot(x, x, "-k")
    plt.title("Output v AHI")
    print findRSquared(x, y)
    for label, xi, yi in zip(labels, x, y):
        plt.annotate(
            label,
            xy=(xi, yi),
            textcoords="offset points",
            ha="right",
            va="bottom",
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
        )
Example #30
0
def add_timeslices():
    times = pylab.array([0, 200, 400, 600, 1000, 1400, 2000, 2800, 3400, 4800])
    for t in times:
        thours = t / 3600.0
        pylab.plot([-400e3, 0.0], [thours, thours], "k")
        pylab.annotate(
            "%s seconds" % t,
            [0.0, thours],
            [30e3, thours],
            arrowprops={"width": 1, "color": "k", "frac": 0.2, "shrink": 0.1},
        )