def main():
    plt.figure(1)
    plt.xlabel("circle(Time)")
    plt.ylabel("raw fluorescence")
    filename = sys.argv[1]
    filename2 = sys.argv[2]
    data = readfile(filename)
    parameters = readfile(filename2)
    row, col = data.shape
    # print max(data[row-4])
    newbigger = []
    for rownum in xrange(row):
        newbigger.append(data[rownum][col - 1])
    midnum = caculatemidnum(newbigger)
    data = data / midnum
    if row > 0:
        os.system("clear")
    for rownum in xrange(row):
        args = data[rownum]
        plt.figure(1)
        for i in xrange(col):
            plt.plot(i + 1, args[i], marker=".")
    x = np.linspace(0, 90, 100)
    for rownum in xrange(row):
        xopt4 = parameters[rownum]
        y = (
            xopt4[0]
            + xopt4[1] * x
            + xopt4[2] / ((1 + np.exp(-xopt4[3] * (x - xopt4[4]))) * (1 + np.exp(-xopt4[5] * (x - xopt4[6]))))
        )
        plt.figure(1)
        plt.plot(x, y)

    plt.show()
Example #2
1
def plot_benchmark_PR_curves(r_cnn, p_cnn, r_outlier, p_outlier, r_mean, p_mean, r_sc, p_sc, nblast, plotdir, key):

    sns.set(style="white")
    curr_palette = sns.color_palette()
    col1 = curr_palette[2]
    col2 = curr_palette[1]
    col3 = curr_palette[0]
    col4 = curr_palette[3]

    plt.clf()
    f, ax = plt.subplots()
    plt.plot(r_cnn, p_cnn, c=col1, label="CellCnn")
    plt.plot(r_outlier, p_outlier, c=col2, label="outlier")
    plt.plot(r_mean, p_mean, c=col3, label="mean")
    plt.plot(r_sc, p_sc, c=col4, label="sc")
    plt.xlabel("Recall", fontsize=28)
    plt.ylabel("Precision", fontsize=28)
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.05])
    plt.legend(loc="center left", prop={"size": 24})
    for item in ax.get_xticklabels() + ax.get_yticklabels():
        item.set_fontsize(24)
    plt.tight_layout()
    sns.despine()
    mkdir_p(plotdir)
    plt.savefig(os.path.join(plotdir, str(nblast) + "_PR_curve.eps"), format="eps")
    plt.close()
Example #3
1
 def plotOutputs(self, _h5data):
     count = 0
     indexMapping = {}
     for i, meas in enumerate(self.outputs.get_varNames()):
         print "[%d] %s" % (i, meas)
         indexMapping[count] = i
         count += 1
     try:
         value = raw_input("Select which variable do you want to plot: ")
         lindex = value.split()
     except ValueError:
         print "Mal! Mal! Mal! Verdadera mal! Por no decir borchenoso!"
     values = []
     for idx in lindex:
         idx = int(idx)
         values.append(self.outputs.get_varNames()[indexMapping[idx]])
     plt.figure(1)
     for meas in values:
         lasenyal = _h5data.get_senyal(meas)
         plt.plot(lasenyal.get_sampleTime(), lasenyal.get_signalReal())
     plt.legend(values)
     plt.ylabel(lasenyal.component)
     plt.xlabel("Time (s)")
     plt.grid(b=True, which="both")
     plt.show()
    def solve(self, a=0, b=1, c=0, d=1, n=41, m=41, delta=10 ** -8, h=10 ** -10):
        self.n = n
        self.m = m
        self.hS = (b - a) / (n - 1)
        self.hX = (d - c) / (m - 1)
        self.h = h
        s = linspace(a, b, n)
        x = linspace(c, d, m)

        K = array(self.K(x, s))
        u = dot(K, self.z(s)) * self.hS

        # Начальное приближение
        z = random.random_sample((n,)) * -10
        alpha = 0.01

        z_min, alpha = self.chords_method(K, z, u, alpha, delta, h)
        print("z_min=", z_min, "alpha=", alpha)

        # Рисуем график
        plt.plot(s, self.z(s), s, z_min, "ro")
        plt.title(u"Минимизация функционала Тихонова", family="verdana")
        plt.xlabel("s")
        plt.ylabel("z(s)")
        plt.legend((r"$z_0$", r"$z_\eta^\alpha$"), loc=(0.85, 0.85))
        plt.grid()
        plt.text(-0.1, -0.1, u"Время выполнения: %.3f секунд" % (time.time() - time_l), family="verdana", size=8)
        plt.show()
def plot_sat_mod_plume(sat, mod, month, tmin, tmax):
    """Plots the plume region off of the Columbia river. """
    plt.figure(figsize=(16, 8))
    plt.subplot(1, 2, 1)
    p1 = plt.pcolor(lon_p, lat_p, sat, vmin=tmin, vmax=tmax, cmap="Spectral_r")
    plt.colorbar(p1, label="Temperature $^o$C")
    plt.plot(coast_x, coast_y, "black")
    plt.xlim(min(lon_p), max(lon_p))
    plt.ylim(min(lat_p), max(lat_p))
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")
    plt.title("Plume, Satellite, " + month + " 2005")

    plt.subplot(1, 2, 2)
    p2 = plt.pcolor(lon_p, lat_p, mod, vmin=tmin, vmax=tmax, cmap="Spectral_r")
    plt.colorbar(p2, label="Temperature $^o$C")
    plt.plot(coast_x, coast_y, "black")
    plt.xlim(min(lon_p), max(lon_p))
    plt.ylim(min(lat_p), max(lat_p))
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")
    plt.title("Plume, SELFE Model, " + month + " 2005")
    plt.tight_layout()
    plt.savefig("Images/Plume/sat_mod_" + month + ".png", dpi=300)
    plt.close()
 def figureEvents(self):
     longitudes = np.array([event.longitude() for event in self.events])
     latitudes = np.array([event.latitude() for event in self.events])
     plt.figure(1)
     plt.clf()
     img = plt.figure()
     plt.plot(longitudes, latitudes, "o", markerfacecolor="k", markeredgecolor="k", markersize=1)
     importantPointsLongitude = []
     importantPointsLatitude = []
     try:
         importantPointsLongitude = [poi.longitude() for poi in self.stops if not isnan(poi.longitude())]
         importantPointsLatitude = [poi.latitude() for poi in self.stops if not isnan(poi.latitude())]
     except AttributeError:
         importantPointsLongitude = []
         importantPointsLatitude = []
     plt.plot(
         importantPointsLongitude,
         importantPointsLatitude,
         "o",
         markerfacecolor="b",
         markeredgecolor="k",
         markersize=10,
     )
     plt.xlabel("Longitude")
     plt.ylabel("Latitude")
     plt.title(
         "Number of events : {0}, Number of Important places : {1}".format(
             len(self.events), len(importantPointsLongitude)
         )
     )
     # img.savefig("image.png",dpi = 500)
     return img
Example #7
1
def make_fish(zoom=False):
    plt.close(1)
    plt.figure(1, figsize=(6, 4))
    plt.plot(plot_limits["pitch"], plot_limits["rolldev"], "-g", lw=3)
    plt.plot(plot_limits["pitch"], -plot_limits["rolldev"], "-g", lw=3)
    plt.plot(pitch.midvals, roll.midvals, ".b", ms=1, alpha=0.7)

    p, r = make_ellipse()  # pitch, off nominal roll
    plt.plot(p, r, "-c", lw=2)

    gf = -0.08  # Fudge on pitch value for illustrative purposes
    plt.plot(greta["pitch"] + gf, -greta["roll"], ".r", ms=1, alpha=0.7)
    plt.plot(greta["pitch"][-1] + gf, -greta["roll"][-1], "xr", ms=10, mew=2)

    if zoom:
        plt.xlim(46.3, 56.1)
        plt.ylim(4.1, 7.3)
    else:
        plt.ylim(-22, 22)
        plt.xlim(40, 180)
    plt.xlabel("Sun pitch angle (deg)")
    plt.ylabel("Sun off-nominal roll angle (deg)")
    plt.title("Mission off-nominal roll vs. pitch (5 minute samples)")
    plt.grid()
    plt.tight_layout()
    plt.savefig("fish{}.png".format("_zoom" if zoom else ""))
def part2_4():
    data = np.loadtxt("./data/ex1data1.txt", delimiter=",")
    x = data[:, 0]
    y = data[:, 1]
    m = len(y)
    y = y.reshape(m, 1)
    X = np.c_[np.ones((m, 1)), x]
    theta0_vals = np.linspace(-10, 10, 100)
    theta1_vals = np.linspace(-1, 4, 100)
    J_vals = np.zeros((len(theta0_vals), len(theta1_vals)))
    for i, v0 in enumerate(theta0_vals):
        for j, v1 in enumerate(theta1_vals):
            t = np.array((v0, v1))
            J_vals[i, j] = compute_cost(X, y, t)[0]

    fig = plt.figure()
    ax = fig.gca(projection="3d")
    R, P = np.meshgrid(theta0_vals, theta1_vals)
    ax.plot_surface(R, P, J_vals)
    plt.savefig("2-4_surface.png")

    fig = plt.figure()
    plt.contour(R, P, J_vals.T, np.logspace(-2, 3, 20))
    plt.xlabel(r"${\Theta}_0$")
    plt.ylabel(r"${\Theta}_1$")
    plt.savefig("2-4_contour.png")
def shots4time(player="Noah", team="CHI", s_date="20091001", f_date="20151231", path="D:\Gal\Work\Results"):
    """ """
    actions_1, played_games_1 = actions_raster(
        players=[player], team=team, s_date=s_date, f_date=f_date, path=path, action=c.Shot
    )
    actions_2, played_games_2 = time_raster(player, team, s_date, f_date, path)
    actions_3, played_games_3 = actions_raster(
        players=[player], team=team, s_date=s_date, f_date=f_date, path=path, action=c.FreeThrow
    )

    plt.hold(1)
    # plt.title(player+','+team)
    # plt.plot(actions_1, played_games_1, 'b.')
    # plt.plot(actions_3, played_games_3, 'm.')

    plt.figure(1)
    plt.plot(actions_histogram(actions_1), "b")
    plt.plot(actions_histogram(actions_2), "r")
    plt.plot(actions_histogram(actions_3), "m")

    plt.figure(2)
    plt.title(player + "," + team)
    plt.figtext(0, 0.5, "blue - shots \n" + "red - presentce on court\n" + "magenta - freethrows")
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_1), 3)), "b")
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_2), 3)), "r")
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_3), 3)), "m")
    plt.xlabel("Time (in half minutes)")
    plt.ylabel("Points")
    plt.grid(axis="x")
    plt.xticks(np.arange(1, 5) * c.Q_LEN / 30)
    plt.show()
def main():
    avg = 0.0
    samples = 0
    values = []

    # Get alpha
    alpha = float(input("IIR alpha (0..1.0): "))

    # Check alpha bounds
    if alpha > 1.0:
        print("Setting alpha to 1.0")
        alpha = 1.0
    if alpha < 0:
        print("Setting alpha to 0.0")
        alpha = 0.0

    # Run the filter until we arrive at 99.9% of newval
    values.append(0.0)
    while avg < 1.0 * 0.999:
        samples += 1
        avg = iirAddValue(avg, alpha, 1.0)
        # Plot value in percent
        values.append(avg / 0.01)
        print("%d: %g" % (samples, avg))

    # Display the results
    plt.title("IIR Response Over Time (Alpha = %g)" % (alpha))
    plt.ylim(0, 110)
    plt.xlabel("Samples")
    plt.ylabel("IIR Output (%)")
    plt.plot(values)
    plt.grid(True)
    plt.show()

    pass
Example #11
0
def my_box_plot(self):
    plt.figure()
    plt.plot(self.data[["Income"]])
    plt.title("Plot of Per Capita GDP in " + str(year))
    plt.xlabel("Country Index")
    plt.ylabel("Per Capita GDP")
    plt.savefig("plot_{}.png".format(self.year))
Example #12
0
def plot_CellCnn_PR_curves(prec, recall, seq, seq_labels, nclust, plotdir, key):
    sns.set(style="white")
    curr_palette = sns.color_palette("Set1", n_colors=len(seq))

    plt.clf()
    f, ax = plt.subplots()
    for i, nblast in enumerate(seq):
        if (seq_labels == []) or (nclust is None):
            plt.plot(recall[nblast], prec[nblast])
        else:
            if nclust[nblast] == (1, 1):
                plt.plot(recall[nblast], prec[nblast], c=curr_palette[i], linestyle="-", label=seq_labels[i])
            else:
                plt.plot(
                    recall[nblast],
                    prec[nblast],
                    c=curr_palette[i],
                    linestyle="--",
                    label=seq_labels[i] + " (%d/%d)" % nclust[nblast],
                )

    plt.xlabel("Recall", fontsize=28)
    plt.ylabel("Precision", fontsize=28)
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.05])
    plt.legend(loc="center left", prop={"size": 20})

    for item in ax.get_xticklabels() + ax.get_yticklabels():
        item.set_fontsize(24)
    plt.tight_layout()
    sns.despine()
    mkdir_p(plotdir)
    plt.savefig(os.path.join(plotdir, key + "_CellCnn_PRcurve.eps"), format="eps")
    plt.close()
Example #13
0
    def _spikes_diagnosis(self, signal_mask=None, navigation_mask=None):
        """Plots a histogram to help in choosing the threshold for
        spikes removal.

        Parameters
        ----------
        signal_mask: boolean array
            Restricts the operation to the signal locations not marked
            as True (masked)
        navigation_mask: boolean array
            Restricts the operation to the navigation locations not
            marked as True (masked).

        See also
        --------
        spikes_removal_tool

        """
        self._check_signal_dimension_equals_one()
        dc = self.data
        if signal_mask is not None:
            dc = dc[..., ~signal_mask]
        if navigation_mask is not None:
            dc = dc[~navigation_mask, :]
        der = np.abs(np.diff(dc, 1, -1))
        plt.figure()
        plt.hist(np.ravel(der.max(-1)), 100)
        plt.xlabel("Threshold")
        plt.ylabel("Counts")
        plt.draw()
Example #14
0
def scatter(x, y, equal=False, xlabel=None, ylabel=None, xinvert=False, yinvert=False):
    """
    Plot a scatter with simple formatting options
    """
    plt.scatter(x, y, 200, color=[0.3, 0.3, 0.3], edgecolors="white", linewidth=1, zorder=2)
    sns.despine()
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    if equal:
        plt.axes().set_aspect("equal")
        plt.plot([0, max([x.max(), y.max()])], [0, max([x.max(), y.max()])], color=[0.6, 0.6, 0.6], zorder=1)
        bmin = min([x.min(), y.min()])
        bmax = max([x.max(), y.max()])
        rng = abs(bmax - bmin)
        plt.xlim([bmin - rng * 0.05, bmax + rng * 0.05])
        plt.ylim([bmin - rng * 0.05, bmax + rng * 0.05])
    else:
        xrng = abs(x.max() - x.min())
        yrng = abs(y.max() - y.min())
        plt.xlim([x.min() - xrng * 0.05, x.max() + xrng * 0.05])
        plt.ylim([y.min() - yrng * 0.05, y.max() + yrng * 0.05])
    if xinvert:
        plt.gca().invert_xaxis()
    if yinvert:
        plt.gca().invert_yaxis()
Example #15
0
    def create(self, matrix, outputfile, xbase=0, ybase=0, xlabel="x axis", ylabel="y axis"):
        """receives a matrix of results.
        first row is the x scale.
        first column are the labes (each row has it's own lable)
        creates a file with name outputfile with the created plot"""
        graphs = len(matrix)  # number of graphs

        labels = [matrix[row][0] for row in range(graphs)]
        data = [matrix[row][1:] for row in range(graphs)]

        for graph in range(1, graphs):
            plt.plot(data[0], data[graph], label=labels[graph], color=self.linecolor[graph])
            # plt.plot(data[0], data[graph], self.linestyle[graph], label=labels[graph], color=self.linecolor[graph])

        if xbase > 1:
            plt.gca().set_xscale("log", basex=xbase)
        if ybase > 1:
            plt.gca().set_yscale("log", basey=ybase)

        plt.xlabel(xlabel)
        plt.ylabel(ylabel)

        plt.legend()

        plt.savefig(outputfile)
Example #16
0
def train_test_plot(data, plot=False):
    trainX, trainY, testX, testY = splitData(data)
    clf = ensemble.GradientBoostingRegressor(**params)
    clf.fit(trainX, trainY)
    mse = mean_squared_error(testY, clf.predict(testX))
    print ("MSE: %.4f" % mse)

    if plot:
        ###############################################################################
        # Plot training deviance

        # compute test set deviance
        test_score = np.zeros((params["n_estimators"],), dtype=np.float64)

        for i, y_pred in enumerate(clf.staged_predict(testX)):
            test_score[i] = clf.loss_(testY, y_pred)

        plt.figure(figsize=(12, 6))
        plt.subplot(1, 2, 1)
        plt.title("Deviance")
        plt.plot(np.arange(params["n_estimators"]) + 1, clf.train_score_, "b-", label="Training Set Deviance")
        plt.plot(np.arange(params["n_estimators"]) + 1, test_score, "r-", label="Test Set Deviance")
        plt.legend(loc="upper right")
        plt.xlabel("Boosting Iterations")
        plt.ylabel("Deviance")

    return clf
def plotROC(predStrengths, classLabels):
    import matplotlib.pyplot as plt

    cur = (1.0, 1.0)  # cursor
    ySum = 0.0  # variable to calculate AUC
    numPosClas = sum(array(classLabels) == 1.0)
    yStep = 1 / float(numPosClas)
    xStep = 1 / float(len(classLabels) - numPosClas)
    sortedIndicies = predStrengths.argsort()  # get sorted index, it's reverse
    fig = plt.figure()
    fig.clf()
    ax = plt.subplot(111)
    # loop through all the values, drawing a line segment at each point
    for index in sortedIndicies.tolist()[0]:
        if classLabels[index] == 1.0:
            delX = 0
            delY = yStep
        else:
            delX = xStep
            delY = 0
            ySum += cur[1]
        # draw line from cur to (cur[0]-delX,cur[1]-delY)
        ax.plot([cur[0], cur[0] - delX], [cur[1], cur[1] - delY], c="b")
        cur = (cur[0] - delX, cur[1] - delY)
    ax.plot([0, 1], [0, 1], "b--")
    plt.xlabel("False positive rate")
    plt.ylabel("True positive rate")
    plt.title("ROC curve for AdaBoost horse colic detection system")
    ax.axis([0, 1, 0, 1])
    plt.show()
    print "the Area Under the Curve is: ", ySum * xStep
Example #18
0
def plot(x, y, lx, ly, order):
    lp = np.poly1d(np.polyfit(lx, ly, 1))
    xx = np.linspace(min(lx), max(lx), num=100)
    if args.title:
        title = args.title
    else:
        title = "Probablity for texts %s\ncategories:%s" % (
            ",".join(map(str, args.text_numbers)),
            ",".join(map(lambda c: category.category_name(c)["category"], categories)),
        )
    alpha = args.alpha
    plt.ylabel("logit %d-gram model Probability" % order)
    plt.xlabel("logit Cloze Empirical Probability")
    plt.title(title)
    plt.plot(xx, lp(xx), "r-")
    plt.scatter(lx, ly, alpha=alpha)
    plt.savefig("plots/%slogit_%d.png" % (args.prefix, order))
    plt.close()
    print "correlation %d-gram vs. cloze:" % order, pearsonr(x, y)[0]
    print "correlation %d-gram vs. cloze:" % order, pearsonr(lx, ly)[0]

    p = np.poly1d(np.polyfit(x, y, 1))
    xx = np.linspace(min(x), max(x), num=100)

    plt.ylabel("%d-gram model Probability" % order)
    plt.xlabel("Cloze Empirical Probability")
    plt.title(title)
    plt.plot(xx, p(xx), "r-")
    plt.scatter(x, y, alpha=alpha)
    plt.savefig("plots/%s%d.png" % (args.prefix, order))
    plt.close()
Example #19
0
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0
    x_max = 1.0
    y_min = 0.0
    y_max = 1.0

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = 0.01  # step size in the mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii] == 0]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii] == 0]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii] == 1]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii] == 1]

    plt.scatter(grade_sig, bumpy_sig, color="b", label="fast")
    plt.scatter(grade_bkg, bumpy_bkg, color="r", label="slow")
    plt.legend()
    plt.xlabel("bumpiness")
    plt.ylabel("grade")

    plt.savefig("test.png")
def plotErrorBars(dict_to_plot, x_lim, y_lim, xlabel, y_label, title, out_file, margin=[0.05, 0.05], loc=2):

    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(y_label)

    if y_lim is None:
        y_lim = [1 * float("Inf"), -1 * float("Inf")]

    max_val_seen_y = y_lim[1] - margin[1]
    min_val_seen_y = y_lim[0] + margin[1]
    print min_val_seen_y, max_val_seen_y
    max_val_seen_x = x_lim[1] - margin[0]
    min_val_seen_x = x_lim[0] + margin[0]
    handles = []
    for k in dict_to_plot:
        means, stds, x_vals = dict_to_plot[k]

        min_val_seen_y = min(min(np.array(means) - np.array(stds)), min_val_seen_y)
        max_val_seen_y = max(max(np.array(means) + np.array(stds)), max_val_seen_y)

        min_val_seen_x = min(min(x_vals), min_val_seen_x)
        max_val_seen_x = max(max(x_vals), max_val_seen_x)

        handle = plt.errorbar(x_vals, means, yerr=stds)
        handles.append(handle)
        print max_val_seen_y
    plt.xlim([min_val_seen_x - margin[0], max_val_seen_x + margin[0]])
    plt.ylim([min_val_seen_y - margin[1], max_val_seen_y + margin[1]])
    plt.legend(handles, dict_to_plot.keys(), loc=loc)
    plt.savefig(out_file)
Example #21
0
def tuning(x, y, err=None, smooth=None, ylabel=None, pal=None):
    """
    Plot a tuning curve
    """
    if smooth is not None:
        xs, ys = smoothfit(x, y, smooth)
        plt.plot(xs, ys, linewidth=4, color="black", zorder=1)
    else:
        ys = asarray([0])
    if pal is None:
        pal = sns.color_palette("husl", n_colors=len(x) + 6)
        pal = pal[2 : 2 + len(x)][::-1]
    plt.scatter(x, y, s=300, linewidth=0, color=pal, zorder=2)
    if err is not None:
        plt.errorbar(x, y, yerr=err, linestyle="None", ecolor="black", zorder=1)
    plt.xlabel("Wall distance (mm)")
    plt.ylabel(ylabel)
    plt.xlim([-2.5, 32.5])
    errTmp = err
    errTmp[isnan(err)] = 0
    rng = max([nanmax(ys), nanmax(y + errTmp)])
    plt.ylim([0 - rng * 0.1, rng + rng * 0.1])
    plt.yticks(linspace(0, rng, 3))
    plt.xticks(range(0, 40, 10))
    sns.despine()
    return rng
def draw_graph(aggregates, aggregates_top):
    """Draws the tweet lifespan graph.

  Keyword Arguments:
  aggregates -- List of percentages of inactive news.
  aggregates_top -- List of percentages of inactive news for top news.
  """
    plots = []
    figure = plt.figure()
    axs = figure.add_subplot(111)

    all_plot = axs.semilogx(_AGGREGATE_HOURS, aggregates)
    plots.append(all_plot)

    top_plot = axs.semilogx(_AGGREGATE_HOURS, aggregates_top, "r--", linewidth=3)
    plots.append(top_plot)

    labels = ["All News", "Top 2% in Popularity"]
    plt.legend(plots, labels, loc=4, ncol=1, columnspacing=0, handletextpad=0)

    plt.grid(True, which="major", linewidth=2)

    plt.xlabel("Passing Hours", fontsize=16)
    plt.ylabel("Inactive News Stories (%)", fontsize=16)

    with open(_GRAPH_DIR + "tweet_lifespan.png", "w") as graph:
        plt.savefig(graph, format="png")
    with open(_GRAPH_DIR + "tweet_lifespan.eps", "w") as graph:
        plt.savefig(graph, format="eps")

    log("Outputted graph!")
    plt.close()
Example #23
0
 def finalize(self):
     plt.clf()
     plt.hist(self.perps, 100, histtype="step")
     plt.xlabel("Perplexity")
     plt.ylabel("Number of Revisions")
     plt.title("Histogram of Revision Perplexities")
     plt.savefig(self.save_name)
def analytic_model_fig(ax, x_range, y_range, h_m, v_m, h_a0, h_a, v_a, lab_op, annotate_string):
    ax.plot(x_range, h_a, "b", linewidth=2)
    ax.plot(x_range, h_a0, "k", x_range, h_m, "r")
    ax.set_ylim(-0.6, 0.6)
    ax.set_xlim(-8.5, 8.5)
    plt.ylabel(r"$h$", fontsize=16)
    plt.yticks([-0.5, 0, 0.5])
    if "x" in lab_op:
        plt.xlabel(r"    $x$", fontsize=16)
    if "y" in lab_op:
        plt.xlabel(r"    $y$", fontsize=16, position=(0.5, -0.5))
    ax1 = ax.twinx()
    ax1.plot(x_range, 0 * x_range, "k--", x_range, v_m, "r--", x_range, v_a, "b--")

    ax1.set_ylim(-1.2, 1.2)
    plt.yticks([-1.0, 0, 1.0])
    ax1.set_xlim(-8.5, 8.5)
    if "u" in lab_op:
        plt.ylabel(r"$u$", fontsize=16)
    if "v" in lab_op:
        plt.ylabel(r"$v$", fontsize=16)
    plt.tight_layout()

    ax.annotate(
        annotate_string,
        xy=(0.01, 0.97),
        xycoords="axes fraction",
        fontsize=12,
        horizontalalignment="left",
        verticalalignment="top",
    )
Example #25
0
def plot_spectrum(t, Fs):
    """
    Plot a spectrum of time series t.

    Lifted from
    http://glowingpython.blogspot.co.uk/2011/08/how-to-plot-frequency-spectrum-with.html

    Parameters
    ----------

    t : ndarray
        Time series of surface elevations.
    Fs : float
        Sampling rate (number of samples per time).

    """

    n = len(t)  # length of the signal
    k = np.arange(n)
    T = n / Fs
    frq = k / T  # two sides frequency range
    frq = frq[range(n / 2)]  # one side frequency range

    Y = np.fft.fft(t) / n  # fft computing and normalization
    Y = Y[range(n / 2)]

    plt.plot(frq, abs(Y), "r")  # plotting the spectrum
    plt.xlabel("Freq (Hz)")
    plt.ylabel("|Y(freq)|")
Example #26
0
def plotting_2d(x, y, hwid):
    bor = 10  # Border of graph in percent, 0 value indicates that the min and max of the data define the boarder
    xlab = "day"  # x-axis label
    ylab = "# columns"  # y-axis label
    plottitle = "Column Defects"  # plot title
    labdata1 = "Fit"  # Label the data
    labdata2 = hwid  # Label the data
    # xmin = min(x) - abs((max(x) - min(x)) * bor / 100) # Sets the scale of the plot
    # xmax = max(x) + abs((max(x) - min(x)) * bor / 100) # Sets the scale of the plot
    # ymin = min(y) - abs((max(y) - min(y)) * bor / 100) # Sets the scale of the plot
    # ymax = max(y) + abs((max(y) - min(y)) * bor / 100) # Sets the scale of the plot
    fig, ax = p.subplots()
    ax.plot(x, y, "o", label=labdata2)

    # A = array([ xi, ones(255)])
    legend = ax.legend(
        loc="upper center", shadow=True
    )  # Now add the legend with some customizations. Could add at loc='best'
    frame = legend.get_frame()
    frame.set_facecolor("0.90")
    for label in legend.get_texts():  # Set the fontsize
        label.set_fontsize("large")
    for label in legend.get_lines():
        label.set_linewidth(1.5)  # the legend line width
    p.ylabel(ylab)
    p.xlabel(xlab)
    # p.axis([xmin, xmax, ymin, ymax])
    p.title(plottitle)
    # p.show()
    location = dir0 + "log/" + hwid + "_column_defects_thresh" + str(threshold) + ".pdf"
    p.savefig(location)
    return
Example #27
0
def plot_KM(stime, censor, g1, pval, figname, format="eps"):
    sns.set_style("white")
    kmf = KaplanMeierFitter()
    f, ax = plt.subplots(figsize=(3, 3))
    np.set_printoptions(precision=2, suppress=False)
    kmf.fit(stime[g1], event_observed=censor[g1], label=["high-risk group"])
    kmf.plot(ax=ax, ci_show=False, show_censors=True)
    kmf.fit(stime[~g1], event_observed=censor[~g1], label=["low-risk group"])
    kmf.plot(ax=ax, ci_show=False, show_censors=True)
    ax.grid(b=False)
    sns.despine()
    plt.ylim(0, 1)
    plt.xlabel("time", fontsize=14)
    plt.ylabel("survival", fontsize=14)
    plt.text(
        0.7,
        0.85,
        "pval = %.2e" % (pval),
        fontdict={"size": 12},
        horizontalalignment="center",
        verticalalignment="center",
        transform=ax.transAxes,
    )
    plt.xticks(rotation=45)
    for item in ax.get_xticklabels() + ax.get_yticklabels():
        item.set_fontsize(10)
    plt.tight_layout()
    plt.savefig(figname, format=format)
    plt.close()
def make_plot(use_offset=False):

    # Curves
    if use_offset:
        offset = 0.56
    else:
        offset = 1.0
    plot.plot(xs * offset, ten_ys, linewidth=linewidth, label=r"$T_{growth} = 10$ $\rm{orbits}$")

    if use_offset:
        offset = 0.33
    else:
        offset = 1.0
    plot.plot(xs * offset, thousand_ys, linewidth=linewidth, label=r"$T_{growth} = 1000$ $\rm{orbits}$")

    # Axes
    if use_offset:
        plot.xlim(0, 2)
    else:
        plot.xlim(0, 3)
    plot.ylim(0, 30)

    # Annotate
    plot.xlabel(r"Distance from Vortex Center: $|r - r_c| / H$", fontsize=fontsize)
    plot.ylabel("Normalized Dust Density", fontsize=fontsize)
    plot.title("Comparing Dust Distributions for\n" + r"$m_p = 1$ $M_J$, $\nu_{disk} = 10^{-7}$", fontsize=fontsize + 1)
    plot.legend(loc="upper right")

    # Save + Show
    plot.savefig("radial_dust_comparison.png", bbox_inches="tight", dpi=my_dpi)
    plot.show()
Example #29
0
def plot_value_function(agent_class, run, i):
    """ Plot the value functions for run i. """
    plt.clf()
    agent = load(agent_class, run)
    state0 = simulator.Simulator().get_state()
    values, qval1, qval2 = [], [], []
    min_range = -SHIFT_VECTOR[i]
    max_range = SCALE_VECTOR[i]
    variables = []
    for j in range(VALUE_STEPS):
        var = max_range * (1.0 * j / VALUE_STEPS) + min_range
        state0[i] = var
        values.append(agent.value_function(state0))
        feat = agent.action_features[0](state0)
        qval1.append(agent.action_weights[0].dot(feat))
        qval2.append(agent.action_weights[1].dot(feat))
        variables.append(var)
    max_val = max(max(qval1), max(qval2), min(values))
    min_val = min(min(qval1), min(qval2), min(values))
    plt.plot(variables, values, "-b", label="$V(s)$")
    plt.plot(variables, qval1, "-r", label="$Q(s, a_1)$")
    plt.plot(variables, qval2, "-g", label="$Q(s, a_2)$")
    plt.axis([min_range, max_range, min_val, max_val])
    plt.legend(loc="lower right")
    plt.xlabel(str(i))
    plt.ylabel("$V$")
    plt.savefig("./runs/" + agent.name + "/value_functions/s" + str(i), bbox_inches="tight")
Example #30
0
def main():
    steps = 2.0 / RESOLUTION
    res = np.arange(-1.0, 1.0, steps, dtype=np.float)
    data = np.random.uniform(-1.0, 1.0, (DATA_SETS, 2))
    # data = np.zeros((DATA_SETS, 2))

    (x1, x2, Eout, bias, var) = compute_stats(data, res)

    print "x1: ", x1
    print "x2: ", x2
    print "Eout: ", Eout
    print "bias: ", bias
    print "var: ", var
    print "Eout - bias - var:", (Eout - bias - var)

    title = "2.24: N = " + str(DATA_SETS)

    plt.plot(res, f(res))
    plt.plot(res, g(res, x1, x2))
    plt.plot([-1, 1], [0, 0])
    plt.title(title)
    plt.xlabel("x1")
    plt.ylabel("x2")

    plt.show()