def show_image(self, name): """Show image on image view :param name: image file path :type name: str """ # size = self.imageView.get_allocation() # pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(name, size.width, size.height) # self.imageView.set_from_pixbuf(pixbuf) old_viewport = self.imageScrolled.get_child() if old_viewport: old_viewport.destroy() old_viewport = self.imageBox.get_child() if old_viewport: old_viewport.destroy() with TiffFile(name) as img: fig = imshow(img.asarray())[0] canvas = FigureCanvas(fig) self.imageScrolled.add_with_viewport(canvas) toolbar = NavigationToolbar(canvas, self.win) self.imageBox.add_with_viewport(toolbar) pyplot.close(fig) self.shape = img.asarray().shape self.xmax.set_range(self.xmin.get_value_as_int() + 1, self.shape[0]) self.ymax.set_range(self.ymin.get_value_as_int() + 1, self.shape[1]) self.imageScrolled.show_all()
def create_window_using_tuple(self, tupl, title): window = Gtk.Window() box = Gtk.VBox() window.add(box) figure = Figure(figsize=(4, 4), dpi=100) canvas = FigureCanvas(figure) box.pack_start(canvas, True, True, 0) toolbar = NavigationToolbar(canvas, window) box.pack_start(toolbar, False, False, 0) subplot = figure.add_subplot(111) amounts = list() dates = list() for row in tupl: amounts.append(row[0]) dates.append(row[1]) subplot.bar(dates, amounts, width=10) subplot.set_xticks(dates) subplot.set_xticklabels(dates) for index, data in enumerate(amounts): subplot.text(x=dates[index], y=data, s=f"{data}", ha='center') figure.autofmt_xdate() subplot.set_title(title) window.set_size_request(400, 300) window.set_title(title) window.set_icon_name('pygtk-posting') window.show_all()
def graphic(funcion, initial_value, iterations): function = Function(funcion) win = Gtk.Window() win.connect("destroy", lambda x: Gtk.main_quit()) win.set_default_size(640, 480) win.set_title("Embedding in GTK") vbox = Gtk.VBox() win.add(vbox) increment = 0.01 final_value = math.fabs(initial_value+math.fabs(increment*100)) fig = Figure(figsize=(5, 4), dpi=100) ax = fig.add_subplot(111) x = np.arange(-50, 3, 0.01) y = [function.evaluate2(i) for i in x] ax.plot(x, y) canvas = FigureCanvas(fig) # a Gtk.DrawingArea vbox.pack_start(canvas, True, True, 0) toolbar = NavigationToolbar(canvas, win) vbox.pack_start(toolbar, False, False, 0) win.show_all() Gtk.main()
def __init__(self, application, size_request=None, style_context=None): """ :param tuple size_request: The size to set for the canvas. """ self.application = application self.style_context = style_context self.config = application.config """A reference to the King Phisher client configuration.""" self.figure, _ = pyplot.subplots() self.figure.set_facecolor(self.get_color('bg', ColorHexCode.WHITE)) self.axes = self.figure.get_axes() self.canvas = FigureCanvas(self.figure) self.manager = None if size_request: self.canvas.set_size_request(*size_request) self.canvas.mpl_connect('button_press_event', self.mpl_signal_canvas_button_pressed) self.canvas.show() self.navigation_toolbar = NavigationToolbar(self.canvas, self.application.get_active_window()) self.popup_menu = Gtk.Menu.new() menu_item = Gtk.MenuItem.new_with_label('Export') menu_item.connect('activate', self.signal_activate_popup_menu_export) self.popup_menu.append(menu_item) menu_item = Gtk.MenuItem.new_with_label('Refresh') menu_item.connect('activate', lambda action: self.refresh()) self.popup_menu.append(menu_item) menu_item = Gtk.CheckMenuItem.new_with_label('Show Toolbar') menu_item.connect('toggled', self.signal_toggled_popup_menu_show_toolbar) self._menu_item_show_toolbar = menu_item self.popup_menu.append(menu_item) self.popup_menu.show_all() self.navigation_toolbar.hide() self._legend = None
def graph_c(funcion, initial_value, last_value): function = Fun(funcion) win = Gtk.Window() win.connect("destroy", lambda x: Gtk.main_quit()) win.set_default_size(640, 480) win.set_title("Embedding in GTK") vbox = Gtk.VBox() win.add(vbox) fig = Figure(figsize=(5, 4), dpi=100) ax = fig.add_subplot(111) x = np.arange(initial_value, last_value) y = [function.evaluate2(i) for i in x] ax.plot(x, y) dev = Fun(derivate_function(funcion)) derivada = [dev.evaluate2(i) for i in x] ax.plot(x, derivada) canvas = FigureCanvas(fig) # a Gtk.DrawingArea vbox.pack_start(canvas, True, True, 0) toolbar = NavigationToolbar(canvas, win) vbox.pack_start(toolbar, False, False, 0) win.show_all() Gtk.main()
def makePlot(x_axis, y_axes, axis_update_callback, is_polar): if len(y_axes) < 1: raise Exception("Plot needs at least one y-axis") if is_polar and len(y_axes) != 1: displayError("Polar plots can't have more than one y-axis") y_axes = [y_axes[0]] fig = Figure(figsize=(5, 4), dpi=100) subplot = None if is_polar: subplot = fig.add_subplot(1, 1, 1, projection='polar') else: subplot = fig.add_subplot(1, 1, 1) #we need to adjust the plot so that we have enough space for extra labels if len(y_axes) > 2: fig.subplots_adjust(right=0.75) #generate all axes subplots = [subplot] for axis in y_axes[1:]: subplots.append(subplot.twinx()) #set labels, etc i = -1 for axis, plot in zip(y_axes, subplots): axis.setUpdateCallback(axis_update_callback) if not is_polar: plot.set_ylabel("%s [%s]" % (axis.name, str(axis.unit))) else: label_position = plot.get_rlabel_position() plot.text(np.radians(label_position + 10), plot.get_rmax() / 2.0, "%s [%s]" % (axis.name, str(axis.unit)), rotation=label_position, ha='center', va='center') if axis.min_val is None and axis.max_val is None: plot.set_ylim(auto=True) else: plot.set_ylim(axis.min_val, axis.max_val) if i >= 0: plot.spines['right'].set_position(('outward', i * 60)) i += 1 subplot.set_xlabel("%s [%s]" % (x_axis.name, str(x_axis.unit))) if x_axis.min_val is None and x_axis.max_val is None: subplot.set_xlim(auto=True) else: subplot.set_xlim(x_axis.min_val, x_axis.max_val) subplot.grid(True) canvas = FigureCanvas(fig) canvas.set_size_request(600, 600) box = Gtk.VBox() toolbar = NavigationToolbar(canvas, box) box.pack_start(canvas, False, False, 0) box.pack_start(toolbar, False, False, 0) return box, canvas, subplots
def __init__(self, text_color): # Init prarent and set up container Gtk.ScrolledWindow.__init__(self, border_width=10) self.text_color = text_color self.set_hexpand(True) self.set_vexpand(True) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) but = Gtk.Box() # Convert string to tuple self.text_color = tuple( map(float, self.text_color.strip('rgba()').split(','))) # Normalize between 0 and 1 for matplotlib self.text_color = tuple(x / 255 for x in self.text_color) self.f = Figure(figsize=(600, 400), dpi=100) # Set figure to be transparent self.f.patch.set_visible(False) self.a = self.f.add_subplot(111, xscale="log", yscale="log", xlabel="t", ylabel="G(t)") self.a.xaxis.label.set_color(self.text_color) self.a.yaxis.label.set_color(self.text_color) # Set the background to be transparent self.a.set_facecolor('None') # Set the colors of the axes to the font colors of the theme self.a.tick_params(labelcolor=self.text_color, color=self.text_color, which='both') for child in self.a.axes.get_children(): if isinstance(child, matplotlib.spines.Spine): child.set_color(self.text_color) # Finalize canvas self.canvas = FigureCanvas(self.f) # Set up toolbar toolbar = NavigationToolbar(self.canvas, self) toolbar.set_orientation(Gtk.Orientation.HORIZONTAL) box.pack_start(toolbar, False, False, 1) box.pack_start(self.canvas, True, True, 0) self.add(box)
def __init__(self, canvas, title): self.build = Gtk.Builder() self.build.add_from_file("bay.glade") self.window_child = self.build.get_object("chart_window") self.window_child.connect("delete_event", self.destroy_my_window) self.sw = self.build.get_object("scrolled_child_chart") self.sw2 = self.build.get_object("scrolled_child_toolbar") self.sw.add(canvas) self.window_child.set_title(title) toolbar = NavigationToolbar(canvas, self.window_child) self.sw2.add(toolbar)
def init_plot(win): dpi = 100 # class matplotlib.figure.Figure(figsize=None, # dpi=None, facecolor=None, # edgecolor=None, linewidth=1.0, # frameon=True, subplotpars=None) fig = Figure(figsize=(3.0, 3.0), dpi=dpi) canvas = FigCanvas(fig) axes = fig.add_subplot(111, label='generic', navigate=True) toolbar = NavigationToolbar(canvas, win) return axes, canvas, toolbar
def ReplaceFigure(self, fig): for element in self.vbox.get_children(): self.vbox.remove(element) self.canvas = FigureCanvas(self.fig) # a Gtk.DrawingArea self.vbox.pack_start(self.canvas, True, True, 0) toolbar = NavigationToolbar(self.canvas, self) self.vbox.pack_start(toolbar, False, False, 10) self.cursor.set_ax(self.fig.get_axes()[0], self.fig.get_axes(), self.ctrlObj) self.fig.canvas.mpl_connect('button_press_event', self.cursor.mouse_Click) self.show_all()
def on_clear_button_clicked(self, widget): self.openEntry.set_text("") self.analysisCombobox.set_active(0) self.filterCombobox.set_active(0) self.tipTiltBtn.set_active(False) for element in self.vbox.get_children(): self.vbox.remove(element) self.fig = Figure(figsize=(5, 4), dpi=100) self.canvas = FigureCanvas(self.fig) # a Gtk.DrawingArea self.vbox.pack_start(self.canvas, True, True, 0) toolbar = NavigationToolbar(self.canvas, self) self.vbox.pack_start(toolbar, False, False, 10) self.show_all()
class main_setup: #initial run variables run0 = hough_params() #generates list to add multiple runs run_list = [run0] #sets initial run to edit current_params = run_list[0] #sets initial preview location(before clicking) preview_position = [500, 500] #builds interface from glade xml file builder = Gtk.Builder() builder.add_from_file("tool_layout.glade") #passes XML's signals to various handlers as described in XML builder.connect_signals(Handler()) #gets the main window as object window = builder.get_object("main_window") #gets box which the matplotlib viewer will be placed in as object viewpane = builder.get_object("viewpane") #gets the listbox of different 'runs' as an object listbox_scroller = builder.get_object('listbox_scroller') scan_listbox = builder.get_object('scan_listbox') #setup listbox inital contents #setup listbox inital contents selected_row = None listbox_contents = [] context = window.get_style_context() color1 = context.get_background_color(Gtk.StateFlags.NORMAL) color1 = (color1.red, color1.blue, color1.green) print(type(color1)) #DrawGraph function from plot_view.py creates an object with setup for main and preview matplotlib diagrams image_plot = DrawGraph(background_color=(color1)) #adds the main diagram (canvas generated by the function above) to the box labelled vewpane viewpane.add(image_plot.canvas) #uses matplotlib event handling function to update preview when main diagram is clicked image_plot.canvas.mpl_connect('button_press_event', Handler.updatezoomonclick) #gets the preview box as object zoom_preview = builder.get_object("zoom_preview") #adds the preview diagram to the box zoom_preview.add(image_plot.zoomcanvas) toolbar = NavigationToolbar(image_plot.canvas, window) plotbuttons = builder.get_object('plotbuttons') plotbuttons.add(toolbar) window.show_all()
def show_result(self, fig): """show data image on resultScrolled :param fig: figure result from list :type fig: matplotlib.figure.Figure """ old_viewport = self.resultScrolled.get_child() if old_viewport: old_viewport.destroy() old_viewport = self.resultBox.get_child() if old_viewport: old_viewport.destroy() canvas = FigureCanvas(fig) self.resultScrolled.add_with_viewport(canvas) toolbar = NavigationToolbar(canvas, self.win) self.resultBox.add_with_viewport(toolbar) self.resultScrolled.show_all()
def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file("plotter.xml") self.window = self.builder.get_object("plotter_window") cdt = plotter.get_dict_from_file("data/test.txt") plt = plotter.get_plot_from_dict(cdt) plt.draw() self.canvas = FigureCanvas(plt.gcf()) self.canvas.set_size_request(750, 550) self.builder.get_object("plotter_plot_scrollable").add_with_viewport( self.canvas) self.toolbar = NavigationToolbar(self.canvas, self.window) self.builder.get_object( "plotter_toolbar_scrollable").add_with_viewport(self.toolbar) self.window.show_all()
def build_imagePanel(self): self.fig = Figure(dpi=100, tight_layout=True) canvas = FigureCanvas(self.fig) self.fig.canvas.mpl_connect('draw_event', self.ondraw) toolbar = NavigationToolbar(canvas, self) children = toolbar.get_children() for i in range(len(children) - 3): children[i].destroy() self.main_ax = None self.x_hist = None self.y_hist = None self.zoom_ax = None box = Gtk.VBox() box.pack_start(canvas, True, True, 0) box.pack_end(toolbar, False, False, 0) return box
def __init__(self): super(MyWindow, self).__init__() # self.set_default_size(800, 600) self.set_title("Embedding matplotlib in Gtk+3") self.connect("destroy", Gtk.main_quit) self.grid = Gtk.Grid() self.add(self.grid) self.fig = Figure(figsize=(5, 4), dpi=100) self.build_figure() self.canvas = FigureCanvas(self.fig) self.canvas.set_size_request(800, 600) # self.canvas.show() self.grid.attach(self.canvas, 0, 0, 1, 1) self.toolbar = NavigationToolbar(self.canvas, self) self.grid.attach(self.toolbar, 0, 1, 1, 1)
def __init__(self): #Creating the Gtk Window Gtk.Window.__init__(self, title="Embedding Matplotlib") #Setting the size of the GTK window as 400,400 self.set_default_size(400, 400) #Readers should find it familiar, as we are creating a matplotlib figure here with a dpi(resolution) 100 self.fig = Figure(figsize=(5, 5), dpi=100) #The axes element, here we indicate we are creating 1x1 grid and putting the subplot in the only cell #Also we are creating a polar plot, therefore we set projection as 'polar self.ax = self.fig.add_subplot(111, projection='polar') #Here, we borrow one example shown in the matplotlib gtk3 cookbook #and show a beautiful bar plot on a circular coordinate system self.theta = linspace(0.0, 2 * pi, 30, endpoint=False) self.radii = 10 * random.rand(30) self.width = pi / 4 * random.rand(30) self.bars = self.ax.bar(self.theta, self.radii, width=self.width, bottom=0.0) #Here defines the color of the bar, as well as setting it to be transparent for r, bar in zip(self.radii, self.bars): bar.set_facecolor(cm.jet(r / 10.)) bar.set_alpha(0.5) #Here we generate the figure self.ax.plot() #Here comes the magic, a Vbox is created #VBox is a containder subclassed from Gtk.Box, and it organizes its child widgets into a single column self.vbox = Gtk.VBox() #After creating the Vbox, we have to add it to the window object itself! self.add(self.vbox) #Creating Canvas which store the matplotlib figure self.canvas = FigureCanvas(self.fig) # a Gtk.DrawingArea # Add canvas to vbox self.vbox.pack_start(self.canvas, True, True, 0) # Creating toolbar, which enables the save function! self.toolbar = NavigationToolbar(self.canvas, self) self.vbox.pack_start(self.toolbar, False, False, 0)
def __init__(self): self.gladefile = "sieci_gui.glade" self.builder = Gtk.Builder() self.builder.add_from_file(self.gladefile) self.builder.connect_signals(UIHandler()) self.window = self.builder.get_object("main_window") self.window.connect("delete-event", UIHandler().onDeleteWindow) xmax = Gdk.Screen.get_default().get_width() ymax = Gdk.Screen.get_default().get_height() self.canvas = FigureCanvas(f) self.builder.get_object("graphscreen").add_with_viewport(self.canvas) self.builder.get_object("logscroll").set_size_request(int(0.3*xmax), int(0.65*ymax)) self.builder.get_object("graphscreen").set_size_request(int(0.4*xmax), int(0.69*ymax)) f.canvas.resize(int(0.35*xmax), int(0.68*ymax)) toolbar = NavigationToolbar(self.canvas, self.window) self.builder.get_object("toolbar_box").pack_start(toolbar, False, False, 0) textview = self.builder.get_object("algorithm_log") textview.set_buffer(current_network.console.get_text_buffer()) self.window.show_all()
def __init__(self): Gtk.VBox.__init__(self, spacing=4, margin=4) self.figure = Figure(tight_layout=True) self.amplitude_ax = self.figure.add_subplot(2, 2, 1) self.phase_ax = self.figure.add_subplot(2, 2, 2) self.zpk_ax = self.figure.add_subplot(2, 2, 3) self.impulse_ax = self.figure.add_subplot(2, 2, 4) self.canvas = FigureCanvas(self.figure) self.canvas.set_size_request(800, 600) self.navigation_toolbar = NavigationToolbar(self.canvas, self) self.pack_start(self.navigation_toolbar, expand=False, fill=True, padding=0) self.pack_start(self.canvas, expand=True, fill=True, padding=0)
def __init__(self, *args, **kwargs): super(PlotHandler, self).__init__(*args, **kwargs) with open('osmnx_pune_1km', 'rb') as f: self.graph = pickle.load(f) self.graph = osmnx.core.add_edge_lengths(self.graph) builder = self.state.builder sw = builder.get_object('GraphArea') nav_box_holder = builder.get_object('plot_box') self.fig, self.ax = osmnx.plot_graph(self.graph, show=False) self.ax.plot() self.canvas = FigureCanvas(self.fig) self.canvas.mpl_connect('button_release_event', self.canvas_click) window = builder.get_object('AppWin') toolbar = NavigationToolbar(self.canvas, window) nav_box_holder.pack_start(toolbar, False, True, 1) sw.add_with_viewport(self.canvas)
def __init__(self, statfile): Gtk.Window.__init__(self) self.connect('key-release-event', self.KeyPressed) self.set_border_width(8) self.set_default_size(1600, 900) self.set_position(Gtk.WindowPosition.CENTER) self.set_title(statfile[-1]) self.statfile = statfile vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8) vbox.set_homogeneous(False) self.add(vbox) hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) hbox.set_homogeneous(True) vbox.pack_end(hbox, False, False, 0) self.entries, self.values = self.ReadData() store = Gtk.ListStore.new([str]) for entry in self.entries: store.append([entry]) self.xCombo = Gtk.ComboBox.new_with_model_and_entry(store) self.yCombo = Gtk.ComboBox.new_with_model_and_entry(store) self.ComboParams(self.xCombo) self.ComboParams(self.yCombo) self.InitCombo('load') self.InitCompletion(self.xCombo) self.InitCompletion(self.yCombo) self.xCon = self.xCombo.connect('changed', self.ComboChanged) self.xCombo.connect('key-release-event', self.ReleaseFocus) self.yCon = self.yCombo.connect('changed', self.ComboChanged) self.yCombo.connect('key-release-event', self.ReleaseFocus) hbox.pack_start(self.xCombo, True, True, 0) hbox.pack_start(self.yCombo, True, True, 0) self.fig = Figure(figsize=(14, 7)) self.ax = self.fig.gca() self.canvas = FigureCanvas(self.fig) self.canvas.set_can_focus(True) vbox.pack_start(self.canvas, True, True, 0) self.PlotType = 'line' self.PlotData('create', self.PlotType, 'linear', 'linear') self.toolbar = NavigationToolbar(self.canvas, self) vbox.pack_start(self.toolbar, False, False, 0)
def on_chrono_display_button_press_event(self, widget, event): if self.View.display_Mode != "chrono": self.View.display_Mode = "chrono" child = self.View.sw.get_child() child1 = self.View.toolbar.get_child() if child != None: self.View.toolbar.remove(child1) self.View.sw.remove(child) self.box.remove(self.View.canvasCarto) self.box = Gtk.Box() self.View.sw.add(self.box) self.box.pack_start(self.View.canvasChrono, True, True, 0) #Add toolbar toolbar = NavigationToolbar(self.View.canvasChrono, self.View.window) self.View.toolbar.add_with_viewport(toolbar) self.View.sw.show_all()
def __init__(self, schedule): Gtk.Window.__init__(self) self.resize(1124, 640) self.connect("delete-event", Gtk.main_quit) nb = Gtk.Notebook() self._nb = nb self._sched = schedule self._pagenames = schedule._schedules.keys() self._pages = dict() self._curperiod = None self._figures = dict() for name in schedule._schedules: fig = schedule._schedules[name].draw() canvas = FigureCanvas(fig) toolbar = NavigationToolbar(canvas, self) canvas.mpl_connect("motion_notify_event", self.on_motion) canvas.mpl_connect("button_press_event", self.on_click) self._figures[name] = fig vbox = Gtk.VBox() vbox.pack_start(toolbar, False, False, 0) vbox.pack_start(canvas, True, True, 0) label = Gtk.Label(name) self._pages[name] = nb.append_page(vbox, label) vbox1 = Gtk.VBox() self._stat = Gtk.Statusbar() self._statcontext = self._stat.get_context_id("default") vbox1.pack_start(nb, True, True, 0) vbox1.pack_start(self._stat, False, False, 0) self.add(vbox1) self.show_all()
def __init__(self, img_data): self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL) self.window.connect("delete_event", self.delete_event) self.window.connect('key_press_event', self.on_key_press_event) self.window.set_default_size(400, 300) self.window.set_title("Gadgetron Image Viewer") self.vbox = Gtk.VBox() self.window.add(self.vbox) self.fig = Figure(figsize=(5, 4), dpi=100) plt.gray() self.ax = self.fig.add_subplot(111) self.img_ax = self.ax.imshow(np.squeeze(np.abs(img_data))) self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.vbox.pack_start(self.canvas, True, True, 0) self.toolbar = NavigationToolbar(self.canvas, self.window) self.vbox.pack_start(self.toolbar, False, False, 0) self.window.show_all()
def __init__(self, application, size_request=None, style_context=None): """ :param tuple size_request: The size to set for the canvas. """ self.logger = logging.getLogger('KingPhisher.Client.Graph.' + self.__class__.__name__[13:]) self.application = application self.style_context = style_context self.config = application.config """A reference to the King Phisher client configuration.""" self.figure, _ = pyplot.subplots() self.figure.set_facecolor(self.get_color('bg', ColorHexCode.WHITE)) self.axes = self.figure.get_axes() self.canvas = FigureCanvas(self.figure) self.manager = None self.minimum_size = (380, 200) """An absolute minimum size for the canvas.""" if size_request is not None: self.resize(*size_request) self.canvas.mpl_connect('button_press_event', self.mpl_signal_canvas_button_pressed) self.canvas.show() self.navigation_toolbar = NavigationToolbar( self.canvas, self.application.get_active_window()) self.popup_menu = managers.MenuManager() self.popup_menu.append('Export', self.signal_activate_popup_menu_export) self.popup_menu.append('Refresh', self.signal_activate_popup_refresh) menu_item = Gtk.CheckMenuItem.new_with_label('Show Toolbar') menu_item.connect('toggled', self.signal_toggled_popup_menu_show_toolbar) self._menu_item_show_toolbar = menu_item self.popup_menu.append_item(menu_item) self.navigation_toolbar.hide() self._legend = None
def invoice_chart_clicked (self, button): window = Gtk.Window() box = Gtk.VBox() window.add (box) from matplotlib.figure import Figure from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar figure = Figure(figsize=(4, 4), dpi=100) canvas = FigureCanvas(figure) # a Gtk.DrawingArea canvas.set_size_request(900, 600) box.pack_start(canvas, True, True, 0) toolbar = NavigationToolbar(canvas, window) box.pack_start(toolbar, False, False, 0) plot = figure.add_subplot(111) labels = list() fractions = list() unpaid = 0 cursor = DB.cursor() cursor.execute("SELECT SUM(amount_due), c.name FROM invoices " "JOIN contacts AS c ON c.id = invoices.customer_id " "WHERE (canceled, paid, posted) = " "(False, False, True) GROUP BY customer_id, c.name " "ORDER BY c.name") for row in cursor.fetchall(): customer_total = row[0] customer_name = row[1] fractions.append(customer_total) labels.append(customer_name) unpaid += 1 if unpaid == 0: labels.append("None") fractions.append(1.00) cursor.close() plot.pie (fractions, labels=labels, autopct='%1.f%%', radius=0.9) window.set_title ('Unpaid invoices pie chart') window.set_icon_name ('pygtk-posting') window.show_all() DB.rollback()
def __init__(self, config, parent, size_request=None): """ :param dict config: The King Phisher client configuration. :param parent: The parent window for this object. :type parent: :py:class:`Gtk.Window` :param tuple size_request: The size to set for the canvas. """ self.config = config """A reference to the King Phisher client configuration.""" self.parent = parent """The parent :py:class:`Gtk.Window` instance.""" self.figure, _ = pyplot.subplots() self.axes = self.figure.get_axes() self.canvas = FigureCanvas(self.figure) self.manager = None if size_request: self.canvas.set_size_request(*size_request) self.canvas.mpl_connect('button_press_event', self.mpl_signal_canvas_button_pressed) self.canvas.show() self.navigation_toolbar = NavigationToolbar(self.canvas, self.parent) self.popup_menu = Gtk.Menu.new() menu_item = Gtk.MenuItem.new_with_label('Export') menu_item.connect('activate', self.signal_activate_popup_menu_export) self.popup_menu.append(menu_item) menu_item = Gtk.MenuItem.new_with_label('Refresh') menu_item.connect('activate', lambda action: self.refresh()) self.popup_menu.append(menu_item) menu_item = Gtk.CheckMenuItem.new_with_label('Show Toolbar') menu_item.connect('toggled', self.signal_toggled_popup_menu_show_toolbar) self._menu_item_show_toolbar = menu_item self.popup_menu.append(menu_item) self.popup_menu.show_all() self.navigation_toolbar.hide()
def setup_matplotlib_widget(self): # TODO Create a mixin for this kind of thing!! #style = Gtk.Style() self.figure = Figure( dpi=72) #, edgecolor=str(style.bg[2]), facecolor=str(style.bg[2])) self.figure.subplots_adjust(bottom=0.20) self.canvas = FigureCanvasGTK(self.figure) box = Gtk.VBox() box.pack_start(NavigationToolbar(self.canvas, self.get_top_widget()), False, True, 0) box.pack_start(self.canvas, True, True, 0) self.graph_parent.add(box) self.graph_parent.show_all() cdict = { 'red': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)) } self.wbw_cmap = matplotlib.colors.LinearSegmentedColormap( 'WBW', cdict, 256)
def drawPlot(self, xvalues, yvalues, xlabel, ylabel, title, color, zones=None, xzones=None, ylimits=None, y1_linewidth=None): logging.debug('>>') logging.debug( "Type: plot | title: %s | col: %s | xlabel: %s | ylabel: %s", title, color, xlabel, ylabel) logging.debug('xlabel: %s | ylabel: %s | title: %s', xlabel, ylabel, title) self.removeVboxChildren() figure = plt.Figure() logging.debug("Figure: %s", figure) #figure.clf() i = 0 for value in xvalues: if i < 1: logging.debug("i: %d, value: (%s) %s %s", i, value, xvalues, yvalues) axis = figure.add_subplot(111) logging.debug("Axis: %s", axis) line = axis.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis plotted, Line: %s", line) if y1_linewidth is not None: line[0].set_linewidth(y1_linewidth) linewidth = line[0].get_linewidth() axis.grid(True) logging.debug("Axis grid on") for tl in axis.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Ticklabels color set") #Draw zones on graph, eg for each lap if xzones is not None: logging.debug("Setting xzones") for xzone in xzones: if xzones.index(xzone) % 2: zonecolor = 'b' else: zonecolor = 'g' axis.axvspan(xzone[0], xzone[1], alpha=0.25, facecolor=zonecolor) maxX = max(xvalues[i]) if i >= 1: ax2 = axis.twinx() logging.debug("Axis2: Axis: %s", ax2) ax2.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis2: plotted") for tl in ax2.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Axis2: Ticklabels color set") maxXt = max(xvalues[i]) if maxXt > maxX: maxX = maxXt axis.set_xlabel(xlabel[i]) logging.debug("X label set") i += 1 axis.set_xlim(0, maxX) if (len(xvalues) > 1): axis.set_title("%s vs %s" % (ylabel[0], ylabel[1])) else: axis.set_title("%s" % (ylabel[0])) ylim_min, ylim_max = axis.get_ylim() if ylimits is not None: logging.debug("Using ylimits: %s", ylimits) if ylimits[0] is not None: ylim_min = ylimits[0] if ylimits[1] is not None: ylim_max = ylimits[1] axis.set_ylim(ylim_min, ylim_max) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea logging.debug("Canvas: %s", canvas) canvas.show() self.vbox.pack_start(canvas, True, True, 0) toolbar = NavigationToolbar(canvas, self.window) self.vbox.pack_start(toolbar, False, False, 0) for child in self.vbox.get_children(): logging.debug('Child available: %s', child) logging.debug('<<') return { 'y1_min': ylim_min, 'y1_max': ylim_max, 'y1_linewidth': linewidth }
from matplotlib.figure import Figure from numpy import arange, sin, pi from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar win = Gtk.Window() win.connect("delete-event", Gtk.main_quit) win.set_default_size(400, 300) win.set_title("Embedding in GTK") f = Figure(figsize=(5, 4), dpi=100) a = f.add_subplot(1, 1, 1) t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) a.plot(t, s) vbox = Gtk.VBox() win.add(vbox) # Add canvas to vbox canvas = FigureCanvas(f) # a Gtk.DrawingArea vbox.pack_start(canvas, True, True, 0) # Create toolbar toolbar = NavigationToolbar(canvas, win) vbox.pack_start(toolbar, False, False, 0) win.show_all() Gtk.main()