本文整理汇总了Python中matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo.show方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasGTK3Cairo.show方法的具体用法?Python FigureCanvasGTK3Cairo.show怎么用?Python FigureCanvasGTK3Cairo.show使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo
的用法示例。
在下文中一共展示了FigureCanvasGTK3Cairo.show方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
def __init__(self, application):
""" Create a summary page containing various statistics such as the number of logs in the logbook, the logbook's modification date, etc.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.application = application
self.logbook = self.application.logbook
self.builder = self.application.builder
glade_file_path = join(realpath(dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("summary_page",))
self.summary_page = self.builder.get_object("summary_page")
self.items = {}
# Database name in large font at the top of the summary page
self.builder.get_object("database_name").set_markup("<span size=\"x-large\">%s</span>" % basename(self.logbook.path))
self.items["LOG_COUNT"] = self.builder.get_object("log_count")
self.items["QSO_COUNT"] = self.builder.get_object("qso_count")
self.items["DATE_MODIFIED"] = self.builder.get_object("date_modified")
# Yearly statistics
config = configparser.ConfigParser()
have_config = (config.read(expanduser('~/.config/pyqso/preferences.ini')) != [])
(section, option) = ("general", "show_yearly_statistics")
if(have_config and config.has_option(section, option)):
if(config.getboolean("general", "show_yearly_statistics") and have_matplotlib):
hbox = Gtk.HBox()
label = Gtk.Label(label="Display statistics for year: ", halign=Gtk.Align.START)
hbox.pack_start(label, False, False, 6)
year_select = Gtk.ComboBoxText()
min_year, max_year = self.get_year_bounds()
if min_year and max_year:
for year in range(max_year, min_year-1, -1):
year_select.append_text(str(year))
year_select.append_text("")
year_select.connect("changed", self.on_year_changed)
hbox.pack_start(year_select, False, False, 6)
self.summary_page.pack_start(hbox, False, False, 4)
self.items["YEARLY_STATISTICS"] = Figure()
canvas = FigureCanvas(self.items["YEARLY_STATISTICS"])
canvas.set_size_request(800, 175)
canvas.show()
self.summary_page.pack_start(canvas, True, True, 0)
# Summary tab label and icon.
tab = Gtk.HBox(homogeneous=False, spacing=0)
label = Gtk.Label(label="Summary ")
icon = Gtk.Image.new_from_icon_name(Gtk.STOCK_INDEX, Gtk.IconSize.MENU)
tab.pack_start(label, False, False, 0)
tab.pack_start(icon, False, False, 0)
tab.show_all()
self.logbook.notebook.insert_page(self.summary_page, tab, 0) # Append as a new tab
self.logbook.notebook.show_all()
return
示例2: run_inner
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
def run_inner(self, endog, exog, **kwargs ):
signs = ['x', '+']
colours = ['r', 'b']
f = plt.figure()
var_index = 0
for var in exog.columns:
sign = signs[var_index % len( signs )]
colour = colours[var_index % len( colours )]
plt.plot( endog, exog[var], colour+sign )
var_index += 1
canvas = FigureCanvas( f )
self.ui.output_vbox.pack_start( canvas, True, True, 0 )
canvas.show()
self.ui.output_dialog.run()
self.ui.output_dialog.hide()
示例3: Pie
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class Pie(ChartBase):
def setup(self):
fig = Figure(figsize=(10, 10), dpi=100, facecolor="white", edgecolor="white")
self.ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.1, right=0.90, top=0.95, bottom=0.05)
# ensure the pie is round
self.ax.set_aspect('equal')
matplotlib.rc('font', family="sans", weight="normal", size=9)
self.plot = FigureCanvas(fig)
self.pack_start(self.plot, True, True, 0)
def draw_plot(self):
self.ax.clear()
self.ax.pie(self.controller.values.values(),
labels=self.controller.values.keys(),
autopct='%1.1f%%',
colors=self.colors
)
# show pie
self.spinner.hide()
self.plot.show()
示例4: StatPerspective
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [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'
#.........这里部分代码省略.........
示例5: GraphBase
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class GraphBase(object):
"""
A basic graph provider for using :py:mod:`matplotlib` to create graph
representations of campaign data. This class is meant to be subclassed
by real providers.
"""
name = 'Unknown'
"""The name of the graph provider."""
name_human = 'Unknown'
"""The human readable name of the graph provider used for UI identification."""
graph_title = 'Unknown'
"""The title that will be given to the graph."""
is_available = True
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
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
@property
def rpc(self):
return self.application.rpc
@staticmethod
def _ax_hide_ticks(ax):
for tick in ax.yaxis.get_major_ticks():
tick.tick1On = False
tick.tick2On = False
@staticmethod
def _ax_set_spine_color(ax, spine_color):
for pos in ('top', 'right', 'bottom', 'left'):
ax.spines[pos].set_color(spine_color)
def add_legend_patch(self, legend_rows, fontsize=None):
if self._legend is not None:
self._legend.remove()
self._legend = None
fontsize = fontsize or self.fontsize_scale
legend_bbox = self.figure.legend(
tuple(patches.Patch(color=patch_color) for patch_color, _ in legend_rows),
tuple(label for _, label in legend_rows),
borderaxespad=1.25,
fontsize=fontsize,
frameon=True,
handlelength=1.5,
handletextpad=0.75,
labelspacing=0.3,
loc='lower right'
)
legend_bbox.legendPatch.set_linewidth(0)
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.
#.........这里部分代码省略.........
示例6: CampaignGraph
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class CampaignGraph(object):
"""
A basic graph provider for using :py:mod:`matplotlib` to create graph
representations of campaign data. This class is meant to be subclassed
by real providers.
"""
name = 'Unknown'
"""The name of the graph provider."""
name_human = 'Unknown'
"""The human readable name of the graph provider used for UI identification."""
graph_title = 'Unknown'
"""The title that will be given to the graph."""
table_subscriptions = []
"""A list of tables from which information is needed to produce the graph."""
is_available = True
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 _load_graph(self, info_cache):
raise NotImplementedError()
def _graph_bar_set_yparams(self, top_lim):
min_value = top_lim + (top_lim * 0.075)
if min_value <= 25:
scale = 5
else:
scale = scale = 10 ** (len(str(int(min_value))) - 1)
inc_scale = scale
while scale <= min_value:
scale += inc_scale
top_lim = scale
ax = self.axes[0]
yticks = set((round(top_lim * 0.5), top_lim))
ax.set_yticks(tuple(yticks))
ax.set_ylim(top=top_lim)
return
def _graph_null_pie(self, title):
ax = self.axes[0]
ax.pie((100,), labels=(title,), colors=(MPL_COLOR_NULL,), autopct='%1.0f%%', shadow=True, startangle=90)
ax.axis('equal')
return
def add_legend_patch(self, legend_rows, fontsize=None):
handles = []
if not fontsize:
scale = self.markersize_scale
if scale < 5:
fontsize = 'xx-small'
elif scale < 7:
fontsize = 'x-small'
elif scale < 9:
fontsize = 'small'
else:
fontsize = 'medium'
for row in legend_rows:
handles.append(patches.Patch(color=row[0], label=row[1]))
self.axes[0].legend(handles=handles, fontsize=fontsize, loc='lower right')
def graph_bar(self, bars, color=None, xticklabels=None, ylabel=None):
"""
Create a standard bar graph with better defaults for the standard use
cases.
:param list bars: The values of the bars to graph.
#.........这里部分代码省略.........
示例7: CampaignGraph
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class CampaignGraph(object):
"""
A basic graph provider for using :py:mod:`matplotlib` to create graph
representations of campaign data. This class is meant to be subclassed
by real providers.
"""
name = 'Unknown'
"""The name of the graph provider."""
name_human = 'Unknown'
"""The human readable name of the graph provider used for UI identification."""
graph_title = 'Unknown'
"""The title that will be given to the graph."""
table_subscriptions = []
"""A list of tables from which information is needed to produce the graph."""
is_available = True
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
@property
def rpc(self):
return self.application.rpc
@staticmethod
def _ax_hide_ticks(ax):
for tick in ax.yaxis.get_major_ticks():
tick.tick1On = False
tick.tick2On = False
@staticmethod
def _ax_set_spine_color(ax, spine_color):
for pos in ('top', 'right', 'bottom', 'left'):
ax.spines[pos].set_color(spine_color)
def _load_graph(self, info_cache):
raise NotImplementedError()
def add_legend_patch(self, legend_rows, fontsize=None):
if self._legend is not None:
self._legend.remove()
self._legend = None
if fontsize is None:
scale = self.markersize_scale
if scale < 5:
fontsize = 'xx-small'
elif scale < 7:
fontsize = 'x-small'
elif scale < 9:
fontsize = 'small'
else:
fontsize = 'medium'
legend_bbox = self.figure.legend(
tuple(patches.Patch(color=patch_color) for patch_color, _ in legend_rows),
tuple(label for _, label in legend_rows),
borderaxespad=1.25,
fontsize=fontsize,
frameon=True,
handlelength=1.5,
handletextpad=0.75,
labelspacing=0.3,
loc='lower right'
)
legend_bbox.legendPatch.set_linewidth(0)
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
#.........这里部分代码省略.........
示例8: SimpleLineChart
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class SimpleLineChart(ChartBase):
def setup(self):
fig = Figure(dpi=100, facecolor="white", edgecolor="white")
self.ax = ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)
# gridlines
ax.yaxis.grid(color='gray')
ax.xaxis.grid(color='gray')
# background
# ax.patch.set_alpha(1)
# font
matplotlib.rc('font', family="sans", weight="normal", size=9)
# frame
ax.set_frame_on(False)
# formatter
formatter = FuncFormatter(gui_utils.get_currency_format_from_float)
ax.yaxis.set_major_formatter(formatter)
formatter = FuncFormatter(self.x_formatter)
ax.xaxis.set_major_formatter(formatter)
self.ax.autoscale(enable=True, axis='both', tight=True)
# annotation
self.annotation = ax.annotate("foo",
xy=(0.0, 0.0), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
color='white',
bbox=dict(boxstyle='round,pad=0.5', color=self.colors[0]),
# arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
)
self.annotation.set_visible(False)
# pack
self.plot = FigureCanvas(fig)
self.pack_start(self.plot, True, True, 0)
# connect events
fig.canvas.mpl_connect('motion_notify_event', self.on_move)
def draw_plot(self):
# remove lines
self.ax.lines = []
# vertical line
self.line = self.ax.axvline(color='gray')
self.line.set_visible(False)
c = 0
x_values = range(len(self.controller.x_values))
for key, val in self.controller.y_values:
while len(val) < len(x_values):
val.append(0.0)
self.ax.plot(x_values,
val,
'o-',
label=key,
color=self.colors[c])
c += 1
# legend
legend = self.ax.legend(loc="best")
# legend.draw_frame(False)
legend.get_frame().set_edgecolor("gray")
# show figure
self.spinner.hide()
self.plot.show()
def on_move(self, event):
if not event.inaxes:
self.line.set_visible(False)
self.annotation.set_visible(False)
event.canvas.draw()
return
x_val = min(int(round(event.xdata, 0)), len(self.controller.x_values) - 1)
self.line.set_xdata(x_val)
self.line.set_visible(True)
self.annotation.set_visible(True)
self.annotation.xy = x_val, event.ydata
text = self.controller.x_values[x_val] + "\n"
for name, vals in self.controller.y_values:
text += name + ": " + gui_utils.get_currency_format_from_float(vals[x_val]) + "\n"
self.annotation.set_text(text)
event.canvas.draw()
示例9: BarChart
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class BarChart(ChartBase):
bar_width = 0.6
def setup(self):
fig = Figure(figsize=(5, 5), dpi=100, facecolor="white", edgecolor="white")
self.ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.2)
# font
matplotlib.rc('font', family="sans", weight="normal", size=9)
# frame
self.ax.set_frame_on(False)
# pack fig
self.plot = FigureCanvas(fig)
self.pack_start(self.plot, True, True, 0)
# connect events
fig.canvas.mpl_connect('motion_notify_event', self.on_move)
def draw_plot(self):
self.ax.clear()
# gridlines
self.ax.yaxis.grid(color='gray')
self.ax.xaxis.grid(color='gray')
# annotation
self.annotation = self.ax.annotate("",
xy=(0.0, 0.0), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
color='white',
bbox=dict(boxstyle='round,pad=0.5', color=self.colors[0]),
# arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
)
self.annotation.set_visible(False)
self.spinner.hide()
pos = range(len(self.controller.x_values))
if len(self.controller.y_values) == 0:
self.plot.show()
return
c = 0
for name, vals in self.controller.y_values:
self.ax.bar(pos,
vals,
width=self.bar_width,
align="center",
facecolor=self.colors[c],
linewidth=0,
label=name)
c += 1
# self.ax.set_xticklabels(self.controller.x_values)
# formatter
formatter = FuncFormatter(gui_utils.get_currency_format_from_float)
self.ax.yaxis.set_major_formatter(formatter)
formatter = FuncFormatter(self.x_formatter)
self.ax.xaxis.set_major_formatter(formatter)
# ensure plots with less than 5 bars look ok
if len(pos) < 5:
self.ax.xaxis.set_ticks(pos)
# legend
legend = self.ax.legend(loc="best")
# legend.draw_frame(False)
legend.get_frame().set_edgecolor("gray")
# recalc limits
self.ax.relim()
self.ax.autoscale_view(True, True, True)
# vertical line
# line needs to be drawn after recalc limits
self.line = self.ax.axvline(color='gray')
self.line.set_visible(False)
# show plot
self.plot.show()
def on_move(self, event):
if not event.inaxes:
self.annotation.set_visible(False)
self.line.set_visible(False)
event.canvas.draw()
return
x_val = min(int(round(event.xdata, 0)), len(self.controller.x_values) - 1)
self.annotation.set_visible(True)
self.line.set_visible(True)
self.line.set_xdata(x_val)
self.annotation.xy = x_val, event.ydata
text = self.controller.x_values[x_val] + "\n"
for name, vals in self.controller.y_values:
text += name + ": " + gui_utils.get_currency_format_from_float(vals[x_val]) + "\n"
#.........这里部分代码省略.........
示例10: __init__
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [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:
#.........这里部分代码省略.........
示例11: Calculator
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class Calculator():
def __init__(self):
self.history_ex = ["","","","","","","","","",""]
self.hisotry_page = [0,0,0,0,0,0,0,0,0,0]
self.x = []
self.y = []
self.init_gui()
def init_gui(self):
self.builder = Gtk.Builder()
self.builder.add_from_file("finally.glade")
self.builder.connect_signals(
{
"window_destroy" : self.window_destroy,
"press_button" : self.press_button,
"clear_text" : self.clear_text,
"remove_last_char": self.remove_last_char,
"calculate" : self.calculate,
"switch_page" : self.switch_page,
"num_base_change" : self.num_base_change,
"fix_cursor" : self.fix_cursor,
"enable_textview" : self.enable_textview,
"disable_textview": self.disable_textview,
"prog_calc" : self.prog_calc,
"back_to_future" : self.back_to_future,
"plot" : self.plot
}
)
self.window = self.builder.get_object("main_window")
self.window.set_size_request(250,305)
self.window.set_title("The Calculator")
self.window.set_icon_from_file("/usr/share/pixmaps/thecalculator-icon.png")
self.text_buff = self.builder.get_object("class_17").get_buffer() # Access buffer from TextView
self.builder.get_object("class_17").grab_focus()
self.builder.get_object("radiobutton3").set_active(True)
self.num_base_change(self.builder.get_object("radiobutton3"))
############### PLOT FUNCTION ##############
sw = self.builder.get_object("scrolledwindow1")
sw2 = self.builder.get_object("scrolledwindow2")
fig = Figure(figsize=(5,5),dpi=120)
self.ax = fig.add_subplot(111)
self.x = arange(-3.1415,3.1415,0.01)
self.y = sin(self.x)
self.ax.plot(self.x,self.y,label="sin(x)")
self.ax.set_xlim(-3.2,3.2)
self.ax.set_ylim(-1.2,1.2)
self.ax.grid(True)
fig.set_size_inches(9.5, 5.5, forward=True)
fig.tight_layout()
self.canvas = FigureCanvas(fig)
sw.add_with_viewport(self.canvas)
self.canvas.show()
toolbar = NavigationToolbar(self.canvas, self.window)
sw2.add_with_viewport(toolbar)
def plot(self,w,data=None,from_x=-10,to_x=10):
text = self.builder.get_object("plot_1").get_text()
y_lim = []
# ([+-]?\d*\.\d+|[+-]?\d+)
# ([+-]?\d{1,})\)
c = search("x_lim=\(([+-]?\d*\.\d+|[+-]?\d+),([+-]?\d*\.\d+|[+-]?\d+)",text)
if (c):
num1 = float(c.group(1))
num2 = float(c.group(2))
print(num1),print(type(num1))
print(num2),print(type(num2))
if ( num1 < num2 ):
print("fees")
from_x=num1
to_x=num2
else:
from_x=num2
to_x=num1
c = search("y_lim=\(([+-]?\d*\.\d+|[+-]?\d+),([+-]?\d*\.\d+|[+-]?\d+)",text)
if (c):
num1 = float(c.group(1))
num2 = float(c.group(2))
if ( num1 < num2 ):
y_lim.append(num1)
y_lim.append(num2)
else:
y_lim.append(num2)
y_lim.append(num1)
self.x = []
self.y = []
self.x = arange(from_x,to_x,0.01)
#.........这里部分代码省略.........
示例12: MainWindow
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, file_path=None):
Gtk.Window.__init__(self)
self.set_default_size(900, 600)
self.set_icon_name(config.PROGRAM_NAME_LOWER)
self.settings = Gio.Settings.new(config.GSETTINGS_BASE_KEY)
self.circuit = None
self.netlist_file_path = None
self.file_monitor = None
self.raw_data_window = console_gui.ConsoleOutputWindow(_("Simulation output"))
self.execution_log_window = console_gui.ConsoleOutputWindow(_("Execution log"))
self._create_menu_models()
##########
#headerbar
self.hb = Gtk.HeaderBar()
self.hb.props.show_close_button = True
if config.csd_are_supported() == True:
self.set_titlebar(self.hb)
else: #disable headerbar as titlebar if not supported
self.no_csd_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.no_csd_box.pack_start(self.hb, False, False, 0)
self.hb.props.show_close_button = False
self.add(self.no_csd_box)
## Right side of headerbar
self.hb_rbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
self._add_insert_button()
self._add_simulate_button()
self._add_gear_button()
self.hb.pack_end(self.hb_rbox)
## Left side of headerbar
self._add_arrow_buttons()
self._add_load_button()
########
#Content
self.stack = Gtk.Stack()
self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
self.stack.set_transition_duration(500)
## Overview stack
self.overview_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.source_view = None
self._open_state("new")
self.infobar = None
self.stack.add_titled(self.overview_box, "overview", _("Circuit"))
## Simulation stack
self.simulation_box = Gtk.Box()
self.canvas = Gtk.DrawingArea()
self.simulation_box.pack_start(self.canvas, True, True, 0)
self.stack.add_titled(self.simulation_box, "simulation", _("Simulation"))
if config.csd_are_supported() == True:
self.add(self.stack)
else: #disable headerbar as titlebar if not supported
self.no_csd_box.pack_end(self.stack, True, True, 0)
self.overview_view()
self.forward_button.props.sensitive = False # HACK: self._open_state("new") sets it to
# False but self.overview_view() sets it to
# True. This line fixes the incongruence.
self.connect_after('destroy', self._on_destroy)
if file_path is not None:
self.load_file(file_path)
def _open_state(self, state="opened"):
"""
show sourceview state="opened" or suggest opening a file state="new"
"""
if state == "opened":
self.overview_view()
self.forward_button.props.sensitive = False # Don go forward until having some simulations
for child in self.overview_box.get_children():
self.overview_box.remove(child)
self.source_scrolled = Gtk.ScrolledWindow(None, None)
self.source_scrolled.set_hexpand(True)
self.source_scrolled.set_vexpand(True)
self.source_buffer = GtkSource.Buffer()
self.source_buffer.connect("modified-changed", self.on_source_buffer_modified_changed)
self.source_buffer.set_highlight_syntax(True)
self.source_buffer.set_language(GtkSource.LanguageManager.get_default().get_language("spice-netlist"))
self.sourceview = GtkSource.View()
self.settings.bind('show-line-numbers', self.sourceview, 'show-line-numbers', Gio.SettingsBindFlags.DEFAULT)
self.settings.bind('highlight-current-line', self.sourceview, 'highlight-current-line', Gio.SettingsBindFlags.DEFAULT)
font_desc = Pango.FontDescription('monospace')
if font_desc:
self.sourceview.modify_font(font_desc)
#.........这里部分代码省略.........
示例13: __init__
# 需要导入模块: from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo [as 别名]
# 或者: from matplotlib.backends.backend_gtk3cairo.FigureCanvasGTK3Cairo import show [as 别名]
#.........这里部分代码省略.........
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))