本文整理汇总了Python中matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo.draw方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasGTK3Cairo.draw方法的具体用法?Python FigureCanvasGTK3Cairo.draw怎么用?Python FigureCanvasGTK3Cairo.draw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo
的用法示例。
在下文中一共展示了FigureCanvasGTK3Cairo.draw方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: EditAtomTypeView
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
class EditAtomTypeView(BaseView):
builder = resource_filename(__name__, "glade/atoms.glade")
top = "edit_atom_type"
widget_format = "atom_%s"
# ------------------------------------------------------------
# Initialisation and other internals
# ------------------------------------------------------------
def __init__(self, *args, **kwargs):
BaseView.__init__(self, *args, **kwargs)
self.graph_parent = self["view_graph"]
self.setup_matplotlib_widget()
def setup_matplotlib_widget(self):
self.figure = Figure(dpi=72)
self.plot = self.figure.add_subplot(111)
self.figure.subplots_adjust(bottom=0.20)
self.matlib_canvas = FigureCanvasGTK(self.figure)
self.plot.autoscale_view()
self.graph_parent.add(self.matlib_canvas)
self.graph_parent.show_all()
# ------------------------------------------------------------
# Methods & Functions
# ------------------------------------------------------------
def update_figure(self, x, y):
self.plot.cla()
self.plot.plot(x, y, 'k-', aa=True)
self.plot.set_ylabel('Scattering factor', size=14, weight="heavy")
self.plot.set_xlabel('2θ', size=14, weight="heavy")
self.plot.autoscale_view()
if self.matlib_canvas is not None:
self.matlib_canvas.draw()
示例2: StatPerspective
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
class StatPerspective(Gtk.Box, Ide.Perspective):
"""
Sets up the stats perspective and handles the signals.
This class sets up the containers of the perspective
and the matplotlib figure and canvas. An asynchronous
method iterates over the project and gathers the data
for the plot.
"""
def __init__(self, workdir, *args, **kwargs):
super().__init__(*args, **kwargs)
self.workdir = workdir
# main containers
scr_win = Gtk.ScrolledWindow(visible=True)
pad_box = Gtk.Box(visible=True)
pad_box.pack_start(scr_win, True, True, 20)
main_box = Gtk.Box(visible=True, orientation=Gtk.Orientation.VERTICAL)
scr_win.add_with_viewport(main_box)
# content
lbl_head = '<span font="36.0"><b>Project Stats</b></span>'
heading = Gtk.Label(label=lbl_head, expand=True, visible=True)
heading.set_use_markup(True)
main_box.pack_start(heading, False, False, 0)
line = Gtk.Separator(visible=True)
main_box.pack_start(line, False, False, 0)
self.fig = Figure(facecolor='none')
self.ax = self.fig.add_subplot(111, axisbg='#ffffff')
self.canvas = FigCanvas(self.fig)
self.canvas.set_size_request(800, 600)
self.canvas.draw()
self.canvas.show()
main_box.pack_start(self.canvas, True, True, 0)
self.add(pad_box)
self.titlebar = Ide.WorkbenchHeaderBar(visible=True)
# Gather stats
thread = threading.Thread(target=self.gather_stats)
thread.daemon = True
thread.start()
def gather_stats(self):
file_types = {}
for root, subfolders, files in os.walk(self.workdir):
for file in files:
try:
with open(root + "/" + file) as fl:
line_count = 0
for line in fl:
line_count += 1
splt_str = file.split(".")
if len(splt_str) > 1:
file_ext = splt_str[-1]
else:
continue
if file_ext in file_types:
# key exists, add line count
file_types[file_ext] = file_types[file_ext] + line_count
else:
# key doesn't exist, create new key
file_types[file_ext] = line_count
except:
continue
keys = []
values = []
for key, value in file_types.items():
keys.append(key)
values.append(value)
key_ar = np.array(keys)
val_ar = np.array(values).astype(int)
ar = np.vstack((key_ar, val_ar)).T
ar = ar[ar[:,1].astype(int).argsort()]
rows = ar.shape[0]
val_pos = np.arange(1, ar.shape[0]+1)
self.ax.barh(val_pos, ar[:,1].astype(int), 0.8, align="center")
# facecolor='yellow'
self.ax.set_yticks(val_pos)
self.ax.tick_params(axis="both", which="major", pad=15)
self.ax.set_yticklabels(ar[:,0], fontsize="16", weight="bold")
self.ax.tick_params(axis="x", which="major", labelsize="16")
self.canvas.set_size_request(800, (rows * 20 + 50))
self.canvas.draw()
def do_get_id(self):
return 'hello-world2'
#.........这里部分代码省略.........
示例3: HP8903BWindow
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
#.........这里部分代码省略.........
for w in self.source_widgets:
w.set_sensitive(True)
if (meas == 4):
for w in self.vsweep_widgets:
w.set_sensitive(True)
if (meas > 1):
self.freq.set_sensitive(True)
self.run_button.set_sensitive(True)
self.action_filesave.set_sensitive(True)
def update_plot(self, x, y):
if (len(self.plt) < 1):
self.plt = self.a.plot(x, y, marker = 'x')
self.plt[0].set_data(x, y)
ymin = min(y)
ymax = max(y)
# if (ymin == 0.0):
# ymin = -0.01
# if (ymax == 0.0):
# ymax = 0.01
sep = abs(ymax - ymin)
sep = sep/10.0
if (sep == 0.0):
sep = 0.01
#self.a.set_ylim((ymin - abs(ymin*0.10), ymax + abs(ymax*0.10)))
self.a.set_ylim((ymin - abs(sep), ymax + abs(sep)))
self.canvas.draw()
def init_hp8903(self):
self.gpib_dev.flush_input()
# Arbitrary but simple measurement to check device
self.gpib_dev.write("FR1000.0HZAP0.100E+00VLM1LNL0LNT3")
status, meas = self.gpib_dev.read(msg_len = 12, timeout = 5000)
if (status):
print(meas)
else:
print("Failed to initialize HP8903!")
print(status, meas)
return(False)
return(True)
def send_measurement(self, meas, unit, freq, amp, filters, ratio = 0):
# Store parameters for saving after any measure
#self.measurements = [amp, filters, meas, unit]
measurement = ""
meas_unit = ""
if (filters[0]):
fs1 = "L1"
elif (filters[1]):
fs1 = "L2"
else:
fs1 = "L0"
if (filters[2]):
fs2 = "H1"
elif (filters[3]):
示例4: Profile
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
class Profile(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Profile")
#f = Figure(figsize=(5,4), dpi=100)
f = Figure()
self.axes = f.add_subplot(111)
self.axes.set_xlabel('Time (sec.)')
self.axes.set_ylabel('Temperature (C)')
self.axes.set_xlim(0, 5*60)
self.axes.set_ylim(20, 300)
self.axes.grid()
self.axes.xaxis.set_major_formatter(FuncFormatter(self.format_xaxis))
self.x = []
self.y = []
self.plot, = self.axes.plot(self.x, self.y, 'o-', picker=5)
self.minutes = False
self.file_name = None
self.canvas = FigureCanvas(f)
self.canvas.set_size_request(800,600)
self.canvas.mpl_connect('button_press_event', self.onclick)
self.canvas.mpl_connect('button_release_event', self.onrelease)
self.canvas.mpl_connect('pick_event', self.onpick)
self.canvas.mpl_connect('motion_notify_event', self.onmotion)
self.picking = None
self.store = Gtk.ListStore(str, str)
self.tree = Gtk.TreeView(self.store)
renderer = Gtk.CellRendererText()
renderer.set_property("editable", True)
renderer.connect('edited', self.on_time_edited)
column = Gtk.TreeViewColumn("Time", renderer, text=0)
self.tree.append_column(column)
renderer = Gtk.CellRendererText()
renderer.set_property("editable", True)
renderer.connect('edited', self.on_temp_edited)
column = Gtk.TreeViewColumn("Temperature", renderer, text=1)
self.tree.append_column(column)
self.box = Gtk.Box()
self.box.pack_start(self.canvas, False, False, 0)
self.box.pack_start(self.tree, True, True, 0)
action_group = Gtk.ActionGroup("profile_actions")
action_group.add_actions([
("FileMenu", None, "File", None, None, None),
("FileNew", Gtk.STOCK_NEW, "_New", "<control>N", None, self.on_file_new),
("FileOpen", Gtk.STOCK_OPEN, "_Open", "<control>O", None, self.on_file_open),
("FileSave", Gtk.STOCK_SAVE, "_Save", "<control>S", None, self.on_file_save),
("FileSaveAs", Gtk.STOCK_SAVE_AS, "Save _As…", "<shift><control>S", None, self.on_file_save_as),
("FileQuit", Gtk.STOCK_QUIT, "_Quit", "<control>Q", None, Gtk.main_quit)
])
uimanager = Gtk.UIManager()
uimanager.add_ui_from_string(UI_INFO)
accelgroup = uimanager.get_accel_group()
self.add_accel_group(accelgroup)
uimanager.insert_action_group(action_group)
menubar = uimanager.get_widget("/MenuBar")
self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.vbox.pack_start(menubar, False, False, 0)
self.vbox.pack_start(self.box, True, True, 0)
self.statusbar = Gtk.Statusbar()
self.status_pos = self.statusbar.get_context_id("position")
self.vbox.pack_start(self.statusbar, False, False, 0)
self.add(self.vbox)
def open_file(self, name):
reader = csv.reader(open(name, 'rb'))
x, y = zip(*reader)
x = [ float(i) for i in x]
y = [ float(i) for i in y]
self.x, self.y = x, y
self.file_name = name
self.set_title('Profile - ' + name)
self.update_data()
self.update_scale()
self.canvas.draw()
def save_file(self, name):
writer = csv.writer(open(name, 'wd'))
writer.writerows(zip(self.x, self.y))
self.file_name = name
self.set_title('Profile - ' + name)
def on_file_new(self, widget):
self.file_name = None
self.set_title('Profile')
self.x = []
self.y = []
self.store.clear()
self.update_data()
self.update_scale()
self.canvas.draw()
def on_file_open(self, widget):
#.........这里部分代码省略.........
示例5: CampaignGraph
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
#.........这里部分代码省略.........
Create a standard bar graph with better defaults for the standard use
cases.
:param list bars: The values of the bars to graph.
:param color: The color of the bars on the graph.
:type color: list, str
:param list xticklabels: The labels to use on the x-axis.
:param str ylabel: The label to give to the y-axis.
:return: The bars created using :py:mod:`matplotlib`
:rtype: `matplotlib.container.BarContainer`
"""
color = color or MPL_COLOR_NULL
width = 0.25
ax = self.axes[0]
self._graph_bar_set_yparams(max(bars) if bars else 0)
bars = ax.bar(range(len(bars)), bars, width, color=color)
ax.set_xticks([float(x) + (width / 2) for x in range(len(bars))])
if xticklabels:
ax.set_xticklabels(xticklabels, rotation=30)
for col in bars:
height = col.get_height()
ax.text(col.get_x() + col.get_width() / 2.0, height, "{0:,}".format(height), ha='center', va='bottom')
if ylabel:
ax.set_ylabel(ylabel)
self.figure.subplots_adjust(bottom=0.25)
return bars
def make_window(self):
"""
Create a window from the figure manager.
:return: The graph in a new, dedicated window.
:rtype: :py:class:`Gtk.Window`
"""
if self.manager == None:
self.manager = FigureManager(self.canvas, 0)
self.navigation_toolbar.destroy()
self.navigation_toolbar = self.manager.toolbar
self._menu_item_show_toolbar.set_active(True)
window = self.manager.window
window.set_transient_for(self.parent)
window.set_title(self.graph_title)
return window
@property
def markersize_scale(self):
bbox = self.axes[0].get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
return max(bbox.width, bbox.width) * self.figure.dpi * 0.01
def mpl_signal_canvas_button_pressed(self, event):
if event.button != 3:
return
self.popup_menu.popup(None, None, None, None, event.button, Gtk.get_current_event_time())
return True
def signal_activate_popup_menu_export(self, action):
dialog = gui_utilities.UtilityFileChooser('Export Graph', self.parent)
file_name = self.config['campaign_name'] + '.png'
response = dialog.run_quick_save(file_name)
dialog.destroy()
if not response:
return
destination_file = response['target_path']
self.figure.savefig(destination_file, format='png')
def signal_toggled_popup_menu_show_toolbar(self, widget):
if widget.get_property('active'):
self.navigation_toolbar.show()
else:
self.navigation_toolbar.hide()
def load_graph(self):
"""Load the graph information via :py:meth:`.refresh`."""
self.refresh()
def refresh(self, info_cache=None, stop_event=None):
"""
Refresh the graph data by retrieving the information from the
remote server.
:param dict info_cache: An optional cache of data tables.
:param stop_event: An optional object indicating that the operation should stop.
:type stop_event: :py:class:`threading.Event`
:return: A dictionary of cached tables from the server.
:rtype: dict
"""
info_cache = (info_cache or {})
if not self.parent.rpc:
return info_cache
for table in self.table_subscriptions:
if stop_event and stop_event.is_set():
return info_cache
if not table in info_cache:
info_cache[table] = tuple(self.parent.rpc.remote_table('campaign/' + table, self.config['campaign_id']))
for ax in self.axes:
ax.clear()
self._load_graph(info_cache)
self.axes[0].set_title(self.graph_title, y=1.03)
self.canvas.draw()
return info_cache
示例6: CampaignGraph
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
#.........这里部分代码省略.........
self._legend = legend_bbox
def get_color(self, color_name, default):
"""
Get a color by its style name such as 'fg' for foreground. If the
specified color does not exist, default will be returned. The underlying
logic for this function is provided by
:py:func:`~.gui_utilities.gtk_style_context_get_color`.
:param str color_name: The style name of the color.
:param default: The default color to return if the specified one was not found.
:return: The desired color if it was found.
:rtype: tuple
"""
color_name = 'theme_color_graph_' + color_name
sc_color = gui_utilities.gtk_style_context_get_color(self.style_context, color_name, default)
return (sc_color.red, sc_color.green, sc_color.blue)
def make_window(self):
"""
Create a window from the figure manager.
:return: The graph in a new, dedicated window.
:rtype: :py:class:`Gtk.Window`
"""
if self.manager is None:
self.manager = FigureManager(self.canvas, 0)
self.navigation_toolbar.destroy()
self.navigation_toolbar = self.manager.toolbar
self._menu_item_show_toolbar.set_active(True)
window = self.manager.window
window.set_transient_for(self.application.get_active_window())
window.set_title(self.graph_title)
return window
@property
def markersize_scale(self):
bbox = self.axes[0].get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
return bbox.width * self.figure.dpi * 0.01
def mpl_signal_canvas_button_pressed(self, event):
if event.button != 3:
return
self.popup_menu.popup(None, None, None, None, event.button, Gtk.get_current_event_time())
return True
def signal_activate_popup_menu_export(self, action):
dialog = gui_utilities.FileChooser('Export Graph', self.application.get_active_window())
file_name = self.config['campaign_name'] + '.png'
response = dialog.run_quick_save(file_name)
dialog.destroy()
if not response:
return
destination_file = response['target_path']
self.figure.savefig(destination_file, format='png')
def signal_toggled_popup_menu_show_toolbar(self, widget):
if widget.get_property('active'):
self.navigation_toolbar.show()
else:
self.navigation_toolbar.hide()
def load_graph(self):
"""Load the graph information via :py:meth:`.refresh`."""
self.refresh()
def refresh(self, info_cache=None, stop_event=None):
"""
Refresh the graph data by retrieving the information from the
remote server.
:param dict info_cache: An optional cache of data tables.
:param stop_event: An optional object indicating that the operation should stop.
:type stop_event: :py:class:`threading.Event`
:return: A dictionary of cached tables from the server.
:rtype: dict
"""
info_cache = (info_cache or {})
if not self.rpc:
return info_cache
for table in self.table_subscriptions:
if stop_event and stop_event.is_set():
return info_cache
if not table in info_cache:
info_cache[table] = tuple(self.rpc.remote_table(table, query_filter={'campaign_id': self.config['campaign_id']}))
for ax in self.axes:
ax.clear()
if self._legend is not None:
self._legend.remove()
self._legend = None
self._load_graph(info_cache)
self.figure.suptitle(
self.graph_title,
color=self.get_color('fg', ColorHexCode.BLACK),
size=14,
weight='bold',
y=0.97
)
self.canvas.draw()
return info_cache
示例7: __init__
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
class UI:
# ====== Variables de la classe UI ========
xn, yn = 0, 0
# =========================================
def __init__(self):
# ### Initialise les datas###
self.array_size = 10
self.nbr_dots = 1
# ###########################
self.builder = Gtk.Builder() # voir commentaires lignes 21-25
# self.builder = gtk.Builder()
self.builder.add_from_file(os.path.join(os.getcwd(), 'TBench_GUI_gl3.ui'))
self.window = self.builder.get_object('dialog1')
self.aboutdialog = self.builder.get_object('aboutdialog1')
self.assistant = self.builder.get_object('assistant1')
self.textview = self.builder.get_object('textview1')
self.textbuffer = self.builder.get_object('textbuffer1')
self.bt_exit = self.builder.get_object('bt_exit')
self.tbt_state0 = self.builder.get_object('tbt_state0')
self.tbt_state1 = self.builder.get_object('tbt_state1')
self.tbt_state2 = self.builder.get_object('tbt_state2')
self.imagemenuitem5 = self.builder.get_object('imagemenuitem5')
self.imagemenuitem10 = self.builder.get_object('imagemenuitem10')
self.builder.connect_signals(self)
self.bufsize = 10 # ajout 20.02
self.databuffer = collections.deque([0.0] * self.bufsize, self.bufsize) # ajout 20.02
self.x = [1 * i for i in range(-self.bufsize + 1, 1)] # ajout 20.02(-self.bufsize+1,1)
# Matplotlib trucs
self.figure = Figure(figsize=(100, 100), dpi=100)
self.ax = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self.figure) # une gtk.DrawingArea
self.line, = self.ax.plot(self.x, self.databuffer)
# Gtk trucs
self.canvas.show()
self.graphview = self.builder.get_object("plot")
self.graphview.pack_start(self.canvas, True, True, True)
self.arrow = self.builder.get_object('arrow1')
self.window.connect('delete-event', self.quit)
self.tbt_state0.connect('toggled', self.on_button_toggled0)
self.tbt_state1.connect('toggled', self.on_button_toggled1)
self.tbt_state2.connect('toggled', self.on_button_toggled2)
self.bt_exit.connect('clicked', self.quit)
self.imagemenuitem5.connect('activate', self.quit)
self.imagemenuitem10.connect('activate', self.show_aboutdialog)
self.window.show()
# ================= Recherche du port de l'arduino ====================
self.sonde = arduino.search()
if self.sonde == "impossible d'ouvrir un port série":
info = (self.sonde + "!" + '\n' +
"quitter cette session, vérifier la connexion avec le PLC, puis relancer le programme")
self.ajout_log_term("TB", info)
else:
self.ajout_log_term("PLC", self.sonde)
self.init_arduino() # initialise l'arduino
# =====================================================================
def updateplot(self):
self.databuffer.append(UI.yn)
self.line.set_ydata(self.databuffer)
self.ax.relim()
self.ax.autoscale_view(False, False, True)
self.canvas.draw()
def on_button_toggled0(self, button):
if button.get_active():
state = ['1', 'on']
button.set_label(state[1].upper())
self.send_command(state[0])
self.updateplot() # pour marquer un temps...
UI.xn = UI.xn + 1
UI.yn = 0.8
else:
state = ['0', 'off']
button.set_label(state[1].upper())
self.send_command(state[0])
self.updateplot() # pour marquer un temps...
UI.xn = UI.xn + 1
UI.yn = 0
# print(UI.xn, UI.yn)
self.updateplot()
# self.updateplot()
# print 'Button0 was turned: ', state[1]
def on_button_toggled1(self, button):
if button.get_active():
state = ['1', 'on']
button.set_label(state[1].upper())
self.send_command(state[0])
else:
state = ['0', 'off']
button.set_label(state[1].upper())
self.send_command(state[0])
def on_button_toggled2(self, button):
if button.get_active():
state = ['1', 'on']
button.set_label(state[1].upper())
self.send_command(state[0])
else:
#.........这里部分代码省略.........
示例8: MyWindow
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
#.........这里部分代码省略.........
# Double last entry to make peak_widths the right length
peak_widths.append(peak_widths[-1])
# Add up spectrum lines from 2D plot where y coord is an order +/-FWHM
# Remember, peak_widths[0] is orders[1]-orders[0].
FWHM = 0.63 # full width half max
spectrum = []
for i in range(len(self.orders)):
peak = int(self.orders[i])
#~ width = int(peak_widths[i]*FWHM)
width = 1
for j in range(0, width):
# Find chord length of circular image
r = len(image[0])/2
start = int(r - (peak * (2*r - peak))**0.5)
end = int(2 * r - start)
for k in range(start, end):
spectrum.append(image[peak-width/2+j][k])
self.update_1D_plot(spectrum)
self.statusbar.push(0, 'Done! ' + self.filename)
@timing
def update_2D_plot(self, image):
self.plot_2D.cla()
self.plot_2D.tick_params(axis='both', labelsize=7)
self.plot_2D.set_title("2D Raw Data")
max = np.amax(image)
self.plot_2D.imshow(image, norm=LogNorm(vmin=0.1, vmax=max/2), origin='lower')
self.canvas.draw()
@timing
def update_orders_plot(self, peaks, orders):
self.plot_orders.cla()
self.plot_orders_line, = self.plot_orders.plot([],[])
self.plot_orders.tick_params(axis='both', labelsize=6)
self.plot_orders.set_title("Orders")
self.plot_orders_line.set_xdata(peaks)
self.plot_orders_line.set_ydata(np.arange(len(peaks)))
self.plot_orders.hlines(orders, min(peaks), max(peaks), color='purple')
self.plot_orders.relim()
self.plot_orders.autoscale_view(True, True, True)
self.canvas.draw()
# Seems a max of 18980 x values are supported by Cairo. Since
# we have more than the max we have to reduce the spectrum
# resolution to fit.
# Maybe do this dynamically based on xlim()?
# xmin, xmax = xlim() # return the current xlim
@timing
def update_1D_plot(self, spectrum):
self.plot_1D.cla()
self.plot_1D_line, = self.plot_1D.plot([],[])
self.plot_1D.set_title("1D Extracted Data")
self.plot_1D.set_xlabel('pixels')
self.plot_1D.set_ylabel('intensity')
self.plot_1D.tick_params(axis='both', labelsize=7)
示例9: ATWindow
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
class ATWindow(Gtk.Window):
def __init__(self, pid):
Gtk.Window.__init__(self, title="Auto-tune")
self.pid = pid
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
f = matplotlib.figure.Figure()
self.axes = f.add_subplot(111)
self.axes.set_xlabel('Time (sec.)')
self.axes.set_ylabel('Temperature (C)')
self.axes.autoscale()
self.out_axes = self.axes.twinx()
self.out_axes.set_ylabel('OUT (%)')
self.out_axes.autoscale()
self.axes.grid()
self.pv_x = []
self.pv_y = []
self.sv_x = []
self.sv_y = []
self.out_x = []
self.out_y = []
self.pv_plot, = self.axes.plot(self.pv_x, self.pv_y, 'b--') #b
self.sv_plot, = self.axes.plot(self.sv_x, self.sv_y, 'k-') #k
self.out_plot, = self.out_axes.plot(self.out_x, self.out_y, 'r:') #r
self.canvas = FigureCanvas(f)
self.canvas.set_size_request(800,600)
vbox.add(self.canvas)
hbox = Gtk.Box()
self.start = Gtk.Button('Start', Gtk.STOCK_EXECUTE)
self.start.connect('clicked', self.on_start)
self.start.set_sensitive(False)
hbox.pack_start(self.start, False, False, 0)
self.stop = Gtk.Button('Stop', Gtk.STOCK_STOP)
self.stop.connect('clicked', self.on_stop)
self.stop.set_sensitive(False)
hbox.pack_start(self.stop, False, False, 0)
button = Gtk.Button('Close', Gtk.STOCK_CLOSE)
button.connect('clicked', self.on_close)
hbox.pack_end(button, False, False, 0)
vbox.add(hbox)
self.add(vbox)
self.run = True
self.start_at = True
self.stop_at = False
self.d = self.loop()
self.d.addErrback(lambda x: None)
self.connect('delete-event', self.on_delete)
def on_start(self, widget):
self.start_at = True
def on_stop(self, widget):
self.stop_at = True
def on_delete(self, widget, event):
self.run = False
def on_close(self, widget):
self.emit('delete-event', None)
self.destroy()
@twisted.internet.defer.inlineCallbacks
def loop(self):
start = time.time()
while self.run:
try:
d = yield self.pid.flags()
active = d['AT']
if active:
self.stop.set_sensitive(True)
self.start.set_sensitive(False)
if self.stop_at:
yield self.pid.coil('NAT')
pv, mult = yield self.pid.holding_read('PV')
self.pv_x.append(time.time() - start)
self.pv_y.append(pv)
self.pv_plot.set_data(self.pv_x, self.pv_y)
self.axes.relim()
self.axes.autoscale()
self.canvas.draw()
sv, mult = yield self.pid.holding_read('dSV')
self.sv_x.append(time.time() - start)
self.sv_y.append(sv)
self.sv_plot.set_data(self.sv_x, self.sv_y)
self.axes.relim()
self.axes.autoscale()
self.canvas.draw()
out, mult = yield self.pid.holding_read('OUT')
self.out_x.append(time.time() - start)
#.........这里部分代码省略.........
示例10: RotationDialog
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
class RotationDialog(object):
"""
This class controls the appearance and signals of the data-rotation dialog.
This class pulls the rotation dialog from the Glade file, intilizes the
widgets and has methods for the signals defined in Glade.
"""
def __init__(self, main_window, settings, data, add_layer_dataset, add_feature, redraw_main):
"""
Initializes the RotationDialog class.
Requires the main_window object, the settings object (PlotSettings
class) and the data rows to initialize. All the necessary widgets are
loaded from the Glade file. A matplotlib figure is set up and added
to the scrolledwindow. Two axes are set up that show the original and
rotated data.
"""
self.builder = Gtk.Builder()
self.builder.set_translation_domain(i18n().get_ts_domain())
script_dir = os.path.dirname(__file__)
rel_path = "gui_layout.glade"
abs_path = os.path.join(script_dir, rel_path)
self.builder.add_objects_from_file(abs_path,
("dialog_rotation", "adjustment_rotation_dipdir",
"adjustment_rotation_dip", "adjustment_rotation_angle"))
self.dialog = self.builder.get_object("dialog_rotation")
self.dialog.set_transient_for(main_window)
self.settings = settings
self.data = data
self.trans = self.settings.get_transform()
self.add_layer_dataset = add_layer_dataset
self.add_feature = add_feature
self.redraw_main = redraw_main
self.adjustment_rotation_dipdir = self.builder.get_object("adjustment_rotation_dipdir")
self.adjustment_rotation_dip = self.builder.get_object("adjustment_rotation_dip")
self.adjustment_rotation_angle = self.builder.get_object("adjustment_rotation_angle")
self.spinbutton_rotation_dipdir = self.builder.get_object("spinbutton_rotation_dipdir")
self.spinbutton_rotation_dip = self.builder.get_object("spinbutton_rotation_dip")
self.spinbutton_rotation_angle = self.builder.get_object("spinbutton_rotation_angle")
self.scrolledwindow_rotate = self.builder.get_object("scrolledwindow_rotate")
self.fig = Figure(dpi=self.settings.get_pixel_density())
self.canvas = FigureCanvas(self.fig)
self.scrolledwindow_rotate.add_with_viewport(self.canvas)
gridspec = GridSpec(1, 2)
original_sp = gridspec.new_subplotspec((0, 0),
rowspan=1, colspan=1)
rotated_sp = gridspec.new_subplotspec((0, 1),
rowspan=1, colspan=1)
self.original_ax = self.fig.add_subplot(original_sp,
projection=self.settings.get_projection())
self.rotated_ax = self.fig.add_subplot(rotated_sp,
projection=self.settings.get_projection())
self.canvas.draw()
self.redraw_plot()
self.dialog.show_all()
self.builder.connect_signals(self)
if sys.platform == "win32":
translate_gui(self.builder)
def run(self):
"""
Runs the dialog.
Called from the MainWindow class. Initializes and shows the dialog.
"""
self.dialog.run()
def on_dialog_rotation_destroy(self, widget):
"""
Hides the dialog on destroy.
When the dialog is destroyed it is hidden.
"""
self.dialog.hide()
def on_button_cancel_rotation_clicked(self, button):
"""
Exits the rotation dialog and makes no changes to the project.
When the user clicks on Cancel the dialog is hidden, and no changes
are made to the project structure.
"""
self.dialog.hide()
def on_button_apply_rotate_clicked(self, button):
"""
Adds the rotated layers to the project.
When the user clicks on "apply the rotation", the rotated data is
added to the project as new datasets.
"""
raxis_dipdir = self.spinbutton_rotation_dipdir.get_value()
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
#.........这里部分代码省略.........
3:'Li',4:'Be',5:'B',6:'C',7:'N', 8:'O',9:'F',10:'Ne',
11:'Na',12:'Mg',13:'Al',14:'Si',15:'P',16:'S',17:'Cl',18:'Ar',
19:'K',20:'Ca'
}
print(ppp)
if os.path.isfile(ppp):
self.load_spc(ppp)
def update_plot(self):
d = self.spc.data[self.cur_depth]
ds = d.species[self.cur_species]
dse = ds.ebindata
dsh = ds.histdata
dsc = ds.rcumdata
#print("NB:",len(dse),len(dsh),len(dsc))
self.ax.cla()
self.ax.set_xlabel('Energy [MeV/u]')
self.ax.set_ylabel('Histories')
# plot legent in upper right corner
text = r'$\mathregular{^{'+str(ds.la)+'}}$'+self.zlut.get(ds.lz,'?')
self.ax.text(0.90, 0.94, text, fontsize=15,transform=self.ax.transAxes)
#self.ax.plot(dse[1:],dsc[1:]) # cumulative sum
self.ax.bar(dse[1:],dsh)
self.canvas.draw()
self.canvas.show()
def onDeleteWindow(self, *args):
Gtk.main_quit(*args)
def onButtonPressed(self, button1):
print("Hello World!")
def main_quit(self, *args):
print("Call Gtk.main_quit")
Gtk.main_quit(*args)
def on_spin1_value_changed(self,*args):
self.cur_depth = self.spin1.get_value_as_int()-1
self.set_labels(self.spc)
self.update_plot()
def on_spin2_value_changed(self,*args):
self.cur_species = self.spin2.get_value_as_int()-1
self.set_labels(self.spc)
self.update_plot()
def on_spin3_value_changed(self,*args):
self.cur_ebin = self.spin3.get_value_as_int()-1
self.set_labels(self.spc)
#self.update_plot() # no need to, as the energy marker is missing.
def on_menuopen_activate(self,*args):
dialog = Gtk.FileChooserDialog("Please choose a file", None,
Gtk.FileChooserAction.OPEN,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
示例12: MyWindow
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
#.........这里部分代码省略.........
global oneDorders
oneDorders = {}
for i in reindex:
zeros1=np.copy(zeros)
zeros1[ len(scidata[0]) - (np.sum(w[(i):18])) : len(scidata[0]) - np.sum(w[(i+1):18]) ] = 1
twoD = scidata*zeros1
# making 2d orders in to 1d orders
Y=[]
for j in range(0,len(scidata[0])):
t = np.sum(twoD[:,j])
Y.append(t)
# placing 1d orders in dictionary called oneDorders
oneDorders[str(i)]=Y
# sending plotting info to update_1dplot for gui (for now using just on order until cross coralation is added to script
self.x = np.linspace(0,len(scidata[0]), num = len(scidata[0]))
self.odo=oneDorders['16']
odo = self.odo[:]
self.update_1dplot(odo,x)
self.save_pickle(oneDorders)
def update_plot(self, scidata):
#self.a.cla()
#cbar.self.a.cla()
self.plt= self.a.imshow(scidata, vmin = 0, vmax = 255,origin = 'lower')
cbar=self.f.colorbar(self.plt,shrink=.84,pad=0.01)
self.canvas.draw()
def update_ordersplot(self,ychunk,xchunk,lines):
## if you dont want to new airglow subtracted data to over plot but to replot, uncomment this next line
self.e.cla()
self.e.set_title("orders")
self.plt=self.e.plot(ychunk,xchunk)
self.e.hlines(lines,0,2000,color='purple',label='centers')
self.canvas.draw()
def update_1dplot(self,odo,x):
## if you dont want to new airglow subtracted data to over plot but to replot, uncomment this next line
self.b.cla()
self.plt=self.b.plot(x,self.odo)
self.canvas.draw()
def update_PHDplot(self,PHD):
## if you dont want to new airglow subtracted data to over plot but to replot, uncomment this next line
self.c.cla()
self.c.set_title('PHD')
self.plt=self.c.hist(PHD,bins=80,histtype='stepfilled')
self.canvas.draw()
## airglow button ##
def buttonbg_clicked(self, widget, data):
dialog = Gtk.FileChooserDialog("Please Choose Airglow File", self,
Gtk.FileChooserAction.OPEN,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
dialog.set_default_response(Gtk.ResponseType.OK)
filter = Gtk.FileFilter()
filter.set_name('fits Files')
示例13: MonitorWindow
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
#.........这里部分代码省略.........
label = Gtk.Label('Step action')
label.set_alignment(0, 0.5)
table.attach(label, 0, 1, row, row+1, yoptions=Gtk.AttachOptions.SHRINK)
label = Gtk.Label()
label.set_alignment(0, 0.5)
table.attach(label, 1, 2, row, row+1, yoptions=Gtk.AttachOptions.SHRINK)
self.status = label
row += 1
main_hbox.add(table)
self.run = True
self.d = self.loop()
self.d.addErrback(lambda x: None)
self.connect('delete-event', self.on_delete)
def on_restart(self, widget):
self.restart = True
def on_delete(self, widget, event):
self.run = False
@twisted.internet.defer.inlineCallbacks
def loop(self):
start = time.time()
while self.run:
if self.restart:
start = time.time()
self.pv_x = []
self.pv_y = []
self.sv_x = []
self.sv_y = []
self.out_x = []
self.out_y = []
self.axes.relim()
self.axes.autoscale()
self.canvas.draw()
self.restart = False
yield self.pid.coil('start')
yield self.pid.coil('auto')
try:
val, mult = yield self.pid.holding_read('Pr+t')
step, step_t = val
val, mult = yield self.pid.holding_read('t-' + ('%02d' % step))
step_total = 0
if type(val) is tuple:
val, idx = val
if val == 'Run':
step_total = idx
elif val == 'Jump':
val += ' to ' + str(abs(idx))
self.current_step.set_text(str(step))
self.step_time.set_text(str(step_t) + '/' + str(step_total) if val == 'Run' else 'NA')
self.status.set_text(val)
pv, mult = yield self.pid.holding_read('PV')
now = time.time() - start
if len(self.pv_y) > 1 and self.pv_y[-2] == self.pv_y[-1] == pv:
self.pv_x[-1] = now
else:
self.pv_x.append(now)
self.pv_y.append(pv)
self.pv_plot.set_data(self.pv_x, self.pv_y)
self.axes.relim()
self.axes.autoscale()
self.canvas.draw()
sv, mult = yield self.pid.holding_read('dSV')
now = time.time() - start
if len(self.sv_y) > 1 and self.sv_y[-2] == self.sv_y[-1] == sv:
self.sv_x[-1] = now
else:
self.sv_x.append(now)
self.sv_y.append(sv)
self.sv_plot.set_data(self.sv_x, self.sv_y)
self.axes.relim()
self.axes.autoscale()
self.canvas.draw()
out, mult = yield self.pid.holding_read('OUT')
now = time.time() - start
if len(self.out_y) > 1 and self.out_y[-2] == self.out_y[-1] == out:
self.out_x[-1] = now
else:
self.out_x.append(now)
self.out_y.append(out)
self.out_plot.set_data(self.out_x, self.out_y)
self.out_axes.relim()
self.out_axes.autoscale()
self.canvas.draw()
except Exception, e:
print 'monitor error', e
traceback.print_exc(file=sys.stdout)
d = twisted.internet.defer.Deferred()
twisted.internet.reactor.callLater(0.300 , d.callback, None)
yield d
示例14: MainClass
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import draw [as 别名]
class MainClass():
def __init__(self):
# Gets all the objects of interest: windows, list boxes, graphviews etc
self.builder = Gtk.Builder()
self.builder.add_from_file('gui/igl-app-window.glade')
self.builder.connect_signals(self)
self.window = self.builder.get_object('window1')
self.sw = self.builder.get_object('graphscrollwindow')
self.sw2 = self.builder.get_object('graphtools')
self.gtbrevealer = self.builder.get_object('graphtoolsrevealer')
self.m1revealer = self.builder.get_object('method1revealer')
self.m2revealer = self.builder.get_object('method2revealer')
self.fnbox = self.builder.get_object('functioncbtext')
self.aentry = self.builder.get_object('aentry')
self.bentry = self.builder.get_object('bentry')
# Use Headerbar for inputs
self.hb = Gtk.HeaderBar()
self.hb.set_show_close_button(True)
self.hb.set_custom_title(self.builder.get_object('titlebox'))
self.window.set_titlebar(self.hb)
# Adds widgets that change the view as per method
self.m1box = guisetup.MethodDetailsBox()
self.m2box = guisetup.MethodDetailsBox()
self.m1revealer.add(self.m1box)
self.m2revealer.add(self.m2box)
self.m1box.mc = self
self.m2box.mc = self
# TODO: Plot as per the defaults to get started
self.fig = Figure(figsize=(5,5), dpi=80)
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
self.sw.add_with_viewport(self.canvas)
self.toolbar = NavigationToolbar(self.canvas, self.window)
self.sw2.add_with_viewport(self.toolbar)
self.on_params_changed(None)
def on_window1_destroy(self, widget):
Gtk.main_quit()
def toggle_allreveal(self, widget):
self.toggle_m1reveal(widget)
self.toggle_m2reveal(widget)
self.toggle_gtbreveal(widget)
# TODO make these change as per the toggle, rather than simply toggling
def toggle_gtbreveal(self, widget):
if self.gtbrevealer.get_reveal_child():
self.gtbrevealer.set_reveal_child(False)
else:
self.gtbrevealer.set_reveal_child(True)
def toggle_m1reveal(self, widget):
if self.m1revealer.get_reveal_child():
self.m1revealer.set_reveal_child(False)
else:
self.m1revealer.set_reveal_child(True)
self.plotexact()
def toggle_m2reveal(self, widget):
if self.m2revealer.get_reveal_child():
self.m2revealer.set_reveal_child(False)
else:
self.m2revealer.set_reveal_child(True)
self.plotexact()
def resetplot(self):
self.ax.cla()
self.ax.grid(True)
def plotexact(self):
self.resetplot()
n = 1000
xs = linspace(self.a, self.b, n+1, endpoint=True)
fxs = self.f(xs)
fxexact = self.ax.plot(xs, fxs, 'k-', label='f(x)')
# def plotapprox(self):
# pass
# TODO: Make these happen somewhere else. Also, make these hide if the method revealer is hidden
if self.m1revealer.get_reveal_child():
fxapprox1 = self.ax.plot(xs, self.m1box.fapprox(xs), 'b-', label='Method 1')
if self.m2revealer.get_reveal_child():
fxapprox2 = self.ax.plot(xs, self.m2box.fapprox(xs), 'r-', label='Method 2')
self.ax.legend()
self.canvas.draw()
#.........这里部分代码省略.........