def draw_plot(x, y, fn, title):
    """
	
	"""

    fig = Figure(figsize=(10, 10), dpi=100)
    axis = fig.add_subplot(1, 1, 1)
    axis.set_title(title)
    axis.set_xlabel("Traits")
    axis.set_ylabel("eQTL size")
    axis.grid(False)
    axis.autoscale(enable=True)

    # axis.set_xlim(0, len(x))
    # axis.set_ylim(0, 5000)

    # for TF_chrom_len in TF_chr_len_list:
    # axis.axvline(TF_chrom_len, color = 'y', alpha = 0.5)

    axis.bar(x, y)
    # axis.set_color('b')

    canvas = FigureCanvas(fig)
    print "Saving file..."
    canvas.print_figure(fn)
Example #2
0
File: views.py Project: LS80/FFL
def player_wp(request, code):
    try:
        player = Player.objects.get(code=code)
    except Player.DoesNotExist:
        raise Http404

    points = player.weekly_points.values_list("points", flat=True)
    response = HttpResponse(content_type="image/png")

    if points:
        weeks = list(player.weekly_points.values_list("week", flat=True))
        fig = Figure(figsize=(0.4 * min(max(10, weeks[-1]), 22), 3), dpi=100, facecolor="white")
        ax = fig.add_subplot(111)
        rects = ax.bar(weeks, points, align="center", linewidth=1, color="#008ad1", width=1)
        ax.set_xlabel("Week")
        ax.set_ylabel("Points")
        ax.set_xticks(weeks)  # add a tick for every week
        for p, rect in zip(points, rects):
            if p != 0:
                if p < 0:
                    h = p * 2 - 1
                elif p > 0:
                    h = p + 1
                ax.text(rect.get_x() + rect.get_width() / 2.0, h, str(p), fontsize=10, color="black", ha="center")
        ax.set_xlim((0.5, max(10, weeks[-1]) + 0.5))
    else:
        fig = Figure(figsize=(1, 1), dpi=1, facecolor="white")  # return one white pixel

    canvas = FigureCanvas(fig)
    canvas.print_png(response)

    return response
def _plot(self, x,y):
	root = Tk.Tk()
	root.wm_title("")


	f = Figure(figsize=(6,6), dpi=100)
	a = f.add_subplot(111)
	t = arange(0.0,3.0,0.01)
	s = sin(2*pi*t)

	a.plot(t,s)


	# a tk.DrawingArea
	canvas = FigureCanvasTkAgg(f, master=root)
	canvas.show()
	canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

	toolbar = NavigationToolbar2TkAgg( canvas, root )
	toolbar.update()
	canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

	def _quit():
    	root.quit()     # stops mainloop
    	root.destroy()  # this is necessary on Windows to prevent
                    # Fatal Python Error: PyEval_RestoreThread: NULL tstate

	button = Tk.Button(master=root, text='Quit', command=_quit)
	button.pack(side=Tk.BOTTOM)

	Tk.mainloop()
	# If you put root.destroy() here, it will cause an error if
	# the window is closed with the window manager.
Example #4
0
File: views.py Project: u1718/cuzco
def gr(request, scan_year, scan_month, scan_day):
    scs = (
        Scan.objects.filter(scan_time__year=scan_year)
        .filter(scan_time__month=scan_month)
        .filter(scan_time__day=scan_day)
    )

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig = Figure(figsize=(16, 6))
    ax = fig.add_subplot(111)
    y = [None for i in range(24 * 60)]
    ta = timezone.datetime(int(scan_year), int(scan_month), int(scan_day))
    tn = ta.replace(tzinfo=timezone.utc)
    x = [tn + timezone.timedelta(minutes=i) for i in xrange(24 * 60)]
    for s in scs:
        y[(s.scan_time - tn).seconds / 60] = s.apoint_set.count()

    ax.plot(x, y, ".")
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type="image/png")
    canvas.print_png(response)
    fig.clear()
    return response
Example #5
0
def end_use(request):
    N = 12
    ind = np.arange(N)  # the x locations for the groups
    width = 0.35
    fig = Figure(figsize=(9, 5), facecolor="w", edgecolor="w")

    ax = fig.add_subplot(221)
    actual = [9, 9, 6, 3, 1, 0, 0, 0, 1, 2, 6, 9]
    ax.bar(ind, actual, 0.35, alpha=1, color="b")
    ax.set_xticks(ind + width)
    ax.set_xticklabels(("E", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"))

    ax = fig.add_subplot(222)
    actual = [0, 0, 0, 0, 2, 3, 6, 6, 3, 2, 1, 0]
    ax.bar(ind, actual, 0.35, alpha=1, color="r")
    ax.set_xticks(ind + width)
    ax.set_xticklabels(("E", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"))

    ax = fig.add_subplot(223)
    actual = [4, 4, 5, 5, 6, 6, 7, 6, 5, 4, 4, 4]
    ax.bar(ind, actual, 0.35, alpha=1, color="y")
    ax.set_xticks(ind + width)
    ax.set_xticklabels(("E", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"))

    ax = fig.add_subplot(224)
    actual = [2, 3, 2, 3, 3, 3, 3, 3, 2, 3, 2, 2]
    ax.bar(ind, actual, 0.35, alpha=1, color="m")
    ax.set_xticks(ind + width)
    ax.set_xticklabels(("E", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"))

    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type="image/png")
    canvas.print_png(response)
    return response
Example #6
0
    def refreshTimeline(self):
        if not self.firstPlot:
            self.figureLayout.removeWidget(self.canvas)

        self.firstPlot = False
        fig = Figure((2.0, 1.5), dpi=100)
        self.canvas = FigureCanvas(fig)
        self.canvas.setParent(self)

        self.ax = fig.add_subplot(111)
        self.ax.clear()

        # levantar el controlDict y ver los tracers

        Tf = float(self.parsedData["endTime"])
        T = float(self.currtime)
        dT = float(self.parsedData["deltaT"])
        self.ax.set_ylim(0, 1.1)
        self.ax.set_xlim(-10 * dT, Tf)
        self.ax.plot([0, T - dT, T, T + dT, Tf], [0, 0, 1, 0, 0], "k", marker="o", label="Current Time")
        i = 0
        for itracer in self.tracersData:
            Tini = float(itracer["startTime"])
            if float(itracer["startTime"]) < T:
                Tini = T
            self.ax.plot([0, Tini, Tini + dT, Tf], [0, 0, 1, 1], self.colors[i % 6], label=itracer["name"])
            i = i + 1
        self.ax.set_title("Timeline")
        self.ax.set_xlabel("Time [s]")
        self.ax.set_ylabel("Event")
        self.ax.legend(loc=0, fontsize="small")

        self.figureLayout.addWidget(self.canvas)
Example #7
0
File: views.py Project: LS80/FFL
def team_wp(request, manager):
    manager = manager.replace("-", " ")
    try:
        team = Team.objects.get(manager__iexact=manager)
    except Team.DoesNotExist:
        raise Http404()

    week = WeekPoints.objects.latest_week()

    points = team.weekly_points.values_list("points", flat=True)
    weeks = range(1, week + 1)

    teams = list(WeekPoints.objects.values_list("points", flat=True))
    shape = (Team.objects.count(), week)
    avgs = mean(reshape(array(teams), shape), axis=0)

    fig = Figure(figsize=(7, 3), dpi=100, facecolor="white")
    ax = fig.add_subplot(111)
    rects = ax.bar(weeks, points, align="center", linewidth=1, color="#008ad1", width=1)
    ax.set_xlabel("Week")
    ax.set_ylabel("Points")
    ax.set_xticks(weeks)  # add a tick for every week
    for rect in rects:
        height = rect.get_height()
        ax.text(
            rect.get_x() + rect.get_width() / 2.0, height / 2.0, str(height), fontsize=10, color="#ffffff", ha="center"
        )
    ax.set_xlim((0.5, max(10, week) + 0.5))
    ax.plot(weeks, avgs, color="blue", marker="*", label="Week average score")
    ax.legend(markerscale=0, handlelength=3)

    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type="image/png")
    canvas.print_png(response)
    return response
Example #8
0
    def graph_data(self):
        if bool(self.preferences_twoplot_var.get()) is False:
            f = Figure(figsize=(15, 6), dpi=100)
            self.graph = f.add_subplot(111)
            self.plot_data, = self.graph.plot(0, 0)

            self.graph_canvas = FigureCanvasTkAgg(f, self)
            self.graph_canvas.show()
            self.graph_canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

            toolbar = NavigationToolbar2TkAgg(self.graph_canvas, self)
            toolbar.update()
            self.graph_canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True)
        else:
            f = Figure(figsize=(15, 6), dpi=100)
            self.graph1 = f.add_subplot(211)
            self.graph2 = f.add_subplot(212)
            self.plot_data_1, = self.graph1.plot(0, 0)
            self.plot_data_2, = self.graph2.plot(0, 0)

            self.graph_canvas = FigureCanvasTkAgg(f, self)
            self.graph_canvas.show()
            self.graph_canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

            toolbar = NavigationToolbar2TkAgg(self.graph_canvas, self)
            toolbar.update()
            self.graph_canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True)
        self.update_graph()
Example #9
0
    def plotConstellationCurve(self):
        row = 0
        constellationCurveFrame = Tk.Frame(root, borderwidth=2, relief="raised", pady=15, padx=10)
        constellationCurveFrame.grid(row=row, column=2, rowspan=9, columnspan=2, sticky=(Tk.N, Tk.W, Tk.E, Tk.S))

        self.calculate = Tk.IntVar()
        self.calculate.set(0)
        calculate = Tk.Checkbutton(
            constellationCurveFrame, text="  Calculate", font=("Helvetica", 12), variable=self.calculate
        ).grid(row=3, column=21, columnspan=2)

        f = Figure(figsize=(4.5, 4.5), dpi=100)
        a = f.add_subplot(111)
        t = (-5, 5)
        s = (-5, 5)
        canvas = FigureCanvasTkAgg(f, constellationCurveFrame)
        canvas.show()
        canvas.get_tk_widget().grid(row=1, column=0, rowspan=6, columnspan=6, sticky=(Tk.N, Tk.W, Tk.E, Tk.S))
        a.plot(t, s, "bs")
        a.axhline(0, color="black")
        a.axvline(0, color="black")
        a.set_title("Constellation Curve")

        save = Tk.Button(
            constellationCurveFrame, text="Save", command=lambda: self.savePlotConstellation(f), bg="cyan"
        ).grid(row=4, column=21, columnspan=2, sticky=(Tk.W, Tk.E))
Example #10
0
    def __init__(self, parent, label_name, topic_name, topic_type, topic_field, buffer_size):

        self.label_name = label_name
        self.topic_type = topic_type
        self.topic_name = topic_name
        self.topic_field = topic_field
        self.buffer_size = buffer_size

        self.timer = QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.update_figure)

        fig = Figure(figsize=(5, 4), dpi=100)
        self.axes = fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        self.compute_initial_figure()
        self.buffer = collections.deque(maxlen=self.buffer_size)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        self.subscriber = RosHelper.create_subscriber_from_type(self.topic_name, self.topic_type, self.on_message)
        self.timer.start()
Example #11
0
def evaluateILD(request):

    ws = Webservice()
    url = "http://localhost:10000/evaluation/evaluate/ild"
    list_result = ws.call_ws(url, request.META["HTTP_USER_AGENT"])

    data = [res["evaluation"] for res in list_result]
    names = [res["name"] for res in list_result]

    cols = ["red", "orange", "yellow", "green", "blue", "purple", "indigo"] * 10
    cols = cols[0 : len(data)]
    fig = Figure(facecolor="white")
    ax = fig.add_subplot(1, 1, 1)
    ind = np.arange(data.__len__())
    ax.bar(ind, data, color=cols)

    ax.set_xticks(ind + 0.4)
    ax.set_xticklabels(names)
    ax.set_yticklabels([])
    ax.set_title("ILD")
    # chart = plt.bar(np.arange(3), data, 0.35)
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type="image/png")
    canvas.print_png(response)
    return response
Example #12
0
def archive_graph(request):
    """ Generates a pie graph to display the number of runs
    that belong to each storage option."""
    # create figure
    figwidth = 3  # inches
    figheight = 3  # inches
    matplotlib.rcParams["font.size"] = 10.0
    matplotlib.rcParams["axes.titlesize"] = 14.0
    matplotlib.rcParams["xtick.labelsize"] = 10.0
    matplotlib.rcParams["legend.fontsize"] = 10.0
    explode = (0.05, 0.0)
    # colors=('b','g')
    fig = Figure(figsize=(figwidth, figheight))
    ax = fig.add_subplot(1, 1, 1)
    runs = models.Experiment.objects.all()
    num_arch = len(runs.filter(storage_options="A"))
    num_del = len(runs.filter(storage_options="D"))
    num_keep = len(runs.filter(storage_options="KI"))
    total = sum([num_arch, num_del, num_keep])
    frac_arch = (float(num_arch) / float(total)) * 100
    frac_del = (float(num_del) / float(total)) * 100
    frac_keep = (float(num_keep) / float(total)) * 100
    frac = [frac_arch, frac_del, frac_keep]
    ax.pie(frac, autopct="%1.f%%", labels=["Archive\n%s" % num_arch, "Delete\n%s" % num_del, "Keep\n%s" % num_keep])
    ax.set_title("Storage Option Breakdown")
    canvas = FigureCanvas(fig)
    response = http.HttpResponse(content_type="image/png")
    canvas.print_png(response)
    return response
Example #13
0
def archive_drivespace(request):
    """Displays as a pie chart, the free vs used space
    on the archive drive.  Will only display if it is mounted"""
    bk = models.BackupConfig.objects.all()[0]  # assume only one configuration possible
    if bk.backup_directory is None:
        return http.HttpResponse()
    path, totalSpace, freeSpace, blocksize = disk_attributes(bk.backup_directory)
    figwidth = 3  # inches
    figheight = 3  # inches
    matplotlib.rcParams["font.size"] = 10.0
    matplotlib.rcParams["axes.titlesize"] = 14.0
    matplotlib.rcParams["xtick.labelsize"] = 10.0
    matplotlib.rcParams["legend.fontsize"] = 10.0
    explode = (0.05, 0.0)
    colors = ("b", "g")
    labels = ["Used", "Free"]
    used_frac = float(totalSpace - freeSpace) / float(totalSpace)
    free_frac = 1 - used_frac
    frac = [used_frac, free_frac]
    fig = Figure(figsize=(figwidth, figheight))
    ax = fig.add_subplot(1, 1, 1)
    # fig.subplots_adjust(wspace=0.5,hspace=0.5,top=0.84)
    ax.pie(frac, autopct="%1.f%%", labels=labels)
    ax.set_title("%s Space" % bk.name)
    canvas = FigureCanvas(fig)
    response = http.HttpResponse(content_type="image/png")
    canvas.print_png(response)
    return response
Example #14
0
    def __init__(self, ticker):
        gtk.VBox.__init__(self)

        startdate = datetime.date(2001, 1, 1)
        today = enddate = datetime.date.today()

        date1 = datetime.date(2011, 1, 1)
        date2 = datetime.date.today()

        mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
        alldays = DayLocator()  # minor ticks on the days
        weekFormatter = DateFormatter("%b %d")  # Eg, Jan 12
        dayFormatter = DateFormatter("%d")  # Eg, 12

        quotes = quotes_historical_yahoo(ticker, date1, date2)
        if len(quotes) == 0:
            raise SystemExit

        fig = Figure(facecolor="white", figsize=(5, 4), dpi=100)
        fig.subplots_adjust(bottom=0.2)
        ax = fig.add_subplot(111)
        ax.xaxis.set_major_locator(mondays)
        ax.xaxis.set_minor_locator(alldays)
        ax.xaxis.set_major_formatter(weekFormatter)
        candlestick(ax, quotes, width=0.6)

        ax.xaxis_date()
        ax.autoscale_view()
        pylab.setp(pylab.gca().get_xticklabels(), rotation=45, horizontalalignment="right")

        canvas = FigureCanvas(fig)  # a gtk.DrawingArea
        self.pack_start(canvas)
        toolbar = NavigationToolbar(canvas, win)
        self.pack_start(toolbar, False, False)
Example #15
0
    def configure_subplots(self, button):
        toolfig = Figure(figsize=(6, 3))
        canvas = self._get_canvas(toolfig)
        toolfig.subplots_adjust(top=0.9)
        tool = SubplotTool(self.canvas.figure, toolfig)

        w = int(toolfig.bbox.width)
        h = int(toolfig.bbox.height)

        window = gtk.Window()
        if window_icon:
            try:
                window.set_icon_from_file(window_icon)
            except:
                # we presumably already logged a message on the
                # failure of the main plot, don't keep reporting
                pass
        window.set_title("Subplot Configuration Tool")
        window.set_default_size(w, h)
        vbox = gtk.VBox()
        window.add(vbox)
        vbox.show()

        canvas.show()
        vbox.pack_start(canvas, True, True)
        window.show()
Example #16
0
class MyWindow(Gtk.ApplicationWindow):
    def __init__(self):

        Gtk.Window.__init__(self, title="Toolbar Example")
        self.set_size_request(700, 500)
        self.box = Gtk.Box(spacing=6, orientation=Gtk.Orientation.VERTICAL)
        self.add(self.box)

        self.fig = Figure()
        self.ax = self.fig.add_subplot(211)
        self.ax.set_xlim(0, 50)
        self.ax.set_ylim(0, 20)

        self.ydata = [0] * 50
        self.line, = self.ax.plot(self.ydata, label="ydata")
        self.ax.legend()

        self.ax2 = self.fig.add_subplot(212)
        self.ydata2 = [0] * 50
        self.color_plot2 = "red"
        self.line2, = self.ax2.plot(self.ydata2, label="ydata2", color=self.color_plot2)
        self.ax2.legend()

        self.f = FigureCanvas(self.fig)
        self.box.pack_start(self.f, True, True, 0)

        self.button = Gtk.Button("Click Me")
        self.button.connect("clicked", self.on_click_me_clicked)
        self.box.pack_start(self.button, False, True, 0)

    def on_click_me_clicked(self, button):
        print "Toller Button"
def sigterm_handler(signum, frame):
    if "solver" in frame.f_globals.iterkeys():
        solver = frame.f_globals["solver"]
        with open("tsp_result.txt", "w") as f:
            length, path = solver.get_result()
            f.write("%d\n" % length)
            for point in path:
                f.write("%d\n" % point)
                # Create a figure with size 6 x 6 inches.
        fig = Figure(figsize=(6, 6))

        # Create a canvas and add the figure to it.
        canvas = FigureCanvas(fig)

        # Create a subplot.
        ax = fig.add_subplot(111)

        # Generate the Scatter Plot.
        ax.scatter([b for a, b, c in solver.input], [c for a, b, c in solver.input], s=20)
        ax.plot(
            [solver.points[i][0] for i in solver.best_path],
            [solver.points[i][1] for i in solver.best_path],
            color="red",
        )
        # Save the generated Scatter Plot to a PNG file.
        canvas.print_figure("graph.png", dpi=500)
    exit(0)
def write_figures(prefix, directory, dose_name, dose_data, data, ec50_coeffs, feature_set, log_transform):
    """Write out figure scripts for each measurement
    
    prefix - prefix for file names
    directory - write files into this directory
    dose_name - name of the dose measurement
    dose_data - doses per image
    data - data per image
    ec50_coeffs - coefficients calculated by calculate_ec50
    feature_set - tuples of object name and feature name in same order as data
    log_transform - true to log-transform the dose data
    """
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_pdf import FigureCanvasPdf

    if log_transform:
        dose_data = np.log(dose_data)
    for i, (object_name, feature_name) in enumerate(feature_set):
        fdata = data[:, i]
        fcoeffs = ec50_coeffs[i, :]
        filename = "%s%s_%s.pdf" % (prefix, object_name, feature_name)
        pathname = os.path.join(directory, filename)
        f = Figure()
        canvas = FigureCanvasPdf(f)
        ax = f.add_subplot(1, 1, 1)
        x = np.linspace(0, np.max(dose_data), num=100)
        y = sigmoid(fcoeffs, x)
        ax.plot(x, y)
        dose_y = sigmoid(fcoeffs, dose_data)
        ax.plot(dose_data, dose_y, "o")
        ax.set_xlabel("Dose")
        ax.set_ylabel("Response")
        ax.set_title("%s_%s" % (object_name, feature_name))
        f.savefig(pathname)
Example #19
0
def png_thread(tn):
    png_fname = "out%d.png" % tn
    vals = 100 + 15 * np.random.randn(10000)

    i = 0
    excp = None
    global exception_raised
    while not exception_raised and i < max_iterations:
        i += 1
        png_f = open(png_fname, "wb")

        try:
            fig = Figure()
            ax = fig.add_subplot(111)
            ax.hist(vals, 50)
            FigureCanvas(fig).print_png(png_f)

        except Exception, excp:
            pass

        png_f.close()
        if excp:
            print "png_thread %d failed on iteration %d:" % (tn, i)
            print traceback.format_exc(excp)
            exception_raised = True
        else:
            print "png_thread %d completed iteration %d." % (tn, i)
 def __init__(self, root, controller):
     f = Figure()
     ax = f.add_subplot(111)
     ax.set_xticks([])
     ax.set_yticks([])
     ax.set_xlim((x_min, x_max))
     ax.set_ylim((y_min, y_max))
     canvas = FigureCanvasTkAgg(f, master=root)
     canvas.show()
     canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     canvas.mpl_connect("key_press_event", self.onkeypress)
     canvas.mpl_connect("key_release_event", self.onkeyrelease)
     canvas.mpl_connect("button_press_event", self.onclick)
     toolbar = NavigationToolbar2TkAgg(canvas, root)
     toolbar.update()
     self.shift_down = False
     self.controllbar = ControllBar(root, controller)
     self.f = f
     self.ax = ax
     self.canvas = canvas
     self.controller = controller
     self.contours = []
     self.c_labels = None
     self.plot_kernels()
Example #21
0
File: views.py Project: LS80/FFL
def graph_plot_png(f, teams, from_week=None, to_week=None):
    to_week = week_to(to_week)
    from_week = week_from(from_week)

    weeks = range(from_week, to_week + 1)

    fig = Figure(figsize=(8, 4), dpi=100, facecolor="white")
    ax = fig.add_subplot(111)

    for team_id in teams:
        team = Team.objects.get(id=team_id)
        points = team.weekly_points.filter(week__in=weeks)
        if not points:
            raise Http404()

        if from_week > 1:
            prev_points = team.weekly_points.filter(week__lt=from_week).aggregate(Sum("points"))["points__sum"]
        else:
            prev_points = 0

        cum_points = cumsum(points.values_list("points", flat=True)) + prev_points

        ax.plot(weeks, cum_points, linewidth=1, label="{0} ({1})".format(team.manager, team.total_points))

    ax.legend(bbox_to_anchor=(1.02, 1), markerscale=0, handlelength=3, loc="upper left")
    ax.set_xlabel("Week")
    ax.set_ylabel("Points")
    ax.set_xticks(weeks)  # add a tick for every week
    ax.set_xlim(from_week, to_week)

    fig.subplots_adjust(left=0.06, right=0.70, top=0.95, bottom=0.08)

    canvas = FigureCanvas(fig)
    canvas.print_png(f)
    return f
Example #22
0
    def __init__(self, parent=None, width=11, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        FigureCanvas.__init__(self, fig)
        # We want the axes cleared every time plot() is called
        self.axes.hold(False)
Example #23
0
def d_anual(request):
    fig = Figure(figsize=(8, 1), facecolor="w", edgecolor="w")
    canvas = FigureCanvas(fig)
    ax = fig.add_axes([0.05, 0.5, 0.9, 0.35])  # Coordenadas del grafico [left,bottom, width, height]

    cmap = mpl.colors.ListedColormap(["b", "r", "y", "m"])
    # cmap.set_over('0.25')
    # cmap.set_under('0.75')
    bounds = [1, 2, 4, 7, 8]
    t_bounds = [0 + (2.0) / 2.0, 2 + (4.0 - 2) / 2, 4 + (7.0 - 4) / 2, 7 + (10.0 - 7) / 2.0]

    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
    cb2 = mpl.colorbar.ColorbarBase(
        ax,
        cmap=cmap,
        boundaries=[0] + bounds + [10],
        norm=norm,
        ticks=t_bounds,
        spacing="proportional",
        orientation="horizontal",
    )
    ##cb2.set_label('Discrete intervals, some other units')
    cb2.ax.set_xticklabels(["R", "C", "I", "O"])
    response = HttpResponse(content_type="image/png")
    canvas.print_png(response)
    return response
Example #24
0
def main():
    filename = "/Users/dalke/databases/compounds_500001_510000.sdf.gz"
    ifs = oemolistream(filename)

    # The figure will be 3 inches by 3 inches
    # Ths size is important because the text is defined relative to
    # inches and not pixels.  In a smaller image the text is more
    # cramped and likely to overlap.  In a larger image the text is
    # not big enough.  This works well for my plot.
    fig = Figure(figsize=(4, 4))

    ax = fig.add_subplot(111)

    cids, weights, xlogps = read_data(ifs, 100)
    ax.scatter(weights, xlogps)
    center, radii = calculate_ellipse_data(weights, xlogps)
    ax.add_patch(Ellipse(center, radii, fill=0, edgecolor="blue"))

    cids, weights, xlogps = read_data(ifs, 100)
    ax.scatter(weights, xlogps, marker="^", color="red")
    center, radii = calculate_ellipse_data(weights, xlogps)
    ax.add_patch(Ellipse(center, radii, fill=0, edgecolor="red"))

    ax.set_xlabel("Atomic weight")
    ax.set_ylabel("CACTVS XLogP")

    # Make the PNG
    canvas = FigureCanvasAgg(fig)
    # The size * the dpi gives the final image size
    #   a4"x4" image * 80 dpi ==> 320x320 pixel image
    canvas.print_figure("mw_v_xlogp_ellipses.png", dpi=80)
Example #25
0
    def configure_subplots(self, button):
        toolfig = Figure(figsize=(6, 3))
        canvas = self._get_canvas(toolfig)
        toolfig.subplots_adjust(top=0.9)
        tool = SubplotTool(self.canvas.figure, toolfig)

        w = int(toolfig.bbox.width)
        h = int(toolfig.bbox.height)

        window = Gtk.Window()
        try:
            window.set_icon_from_file(window_icon)
        except (SystemExit, KeyboardInterrupt):
            # re-raise exit type Exceptions
            raise
        except:
            # we presumably already logged a message on the
            # failure of the main plot, don't keep reporting
            pass
        window.set_title("Subplot Configuration Tool")
        window.set_default_size(w, h)
        vbox = Gtk.Box()
        vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        window.add(vbox)
        vbox.show()

        canvas.show()
        vbox.pack_start(canvas, True, True, 0)
        window.show()
Example #26
0
    def setup(self, layout):
        """ This method creates the graph that is displayed on the top half of
        the user interface.  Currently, the axes are completely hard-coded in
        this method and cannot be changed on-the-fly. """

        figure = Figure(facecolor=Display.background)
        axes = figure.add_subplot(111)

        # In order to create a line object, a dummy line needs to be plotted.
        # This line will get replaced before the GUI is shown to the user.
        pi = numpy.pi
        x = y = self.abscissa

        self.curve = axes.plot(x, y)[0]
        self.canvas = FigureCanvasGTKAgg(figure)

        # The tick labels are formatted using LaTeX.  This makes it possible
        # to use symbols like pi.
        axes.set_xticks((-pi, 0, pi))
        axes.set_xticklabels((r"-pi", "0", r"pi"))
        axes.set_xlim(-pi - 0.25, pi + 0.25)

        axes.set_yticks((0, 1))
        axes.set_yticklabels(("0", "1"))
        axes.set_ylim((-0.1, 1.1))

        layout.pack_start(self.canvas)
 def _figure_default(self):
     """
     figure属性的缺省值,直接创建一个Figure对象
     """
     figure = Figure()
     figure.add_axes([0.1, 0.1, 0.85, 0.80])  # 添加绘图区域,四周留有边距
     return figure
Example #28
0
    def init_window(self):
        if self.window:
            return
        self.window = Gtk.Window(title="Subplot Configuration Tool")

        try:
            self.window.window.set_icon_from_file(window_icon)
        except (SystemExit, KeyboardInterrupt):
            # re-raise exit type Exceptions
            raise
        except:
            # we presumably already logged a message on the
            # failure of the main plot, don't keep reporting
            pass

        self.vbox = Gtk.Box()
        self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        self.window.add(self.vbox)
        self.vbox.show()
        self.window.connect("destroy", self.destroy)

        toolfig = Figure(figsize=(6, 3))
        canvas = self.figure.canvas.__class__(toolfig)

        toolfig.subplots_adjust(top=0.9)
        SubplotTool(self.figure, toolfig)

        w = int(toolfig.bbox.width)
        h = int(toolfig.bbox.height)

        self.window.set_default_size(w, h)

        canvas.show()
        self.vbox.pack_start(canvas, True, True, 0)
        self.window.show()
 def make_derivative_plot(self, file_name):
     derivative_fig = Figure()
     FigureCanvas(derivative_fig)
     derivative_plot = derivative_fig.add_subplot(111)
     derivative_plot.plot(self.dV)
     derivative_plot.axhline(self.seuil, color="m", linestyle="-.", linewidth=2)
     derivative_fig.savefig(file_name)
Example #30
0
    def _make_svg_barchart(self, data, title):

        dpi = 100
        figure_width = 1000 / dpi
        aspect_ratio = 16 / 9
        figure_height = figure_width / aspect_ratio

        figure = Figure(figsize=(figure_width, figure_height), dpi=dpi, facecolor="white")
        axes = figure.add_subplot(1, 1, 1)
        y = data["counts"]
        x = np.arange(len(y))
        width = 0.5
        bar_chart = axes.bar(x, y, width=width, color="r", edgecolor="white")

        axes.set_ylabel("")
        axes.set_title(title, fontsize=20)
        axes.set_xticks(x + width / 2)
        axes.xaxis.set_tick_params(width=0)
        axes.set_xticklabels(data["labels"], rotation=45, fontsize=15)
        axes.grid(axis="y")

        canvas = FigureCanvas(figure)
        image_data = StringIO()
        canvas.print_figure(image_data, format="svg")
        svg = image_data.getvalue()
        svg = svg[svg.find("<svg") :]

        return SvgPlot(svg)