本文整理汇总了Python中matplotlib.figure.Figure.set_tight_layout方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.set_tight_layout方法的具体用法?Python Figure.set_tight_layout怎么用?Python Figure.set_tight_layout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.figure.Figure
的用法示例。
在下文中一共展示了Figure.set_tight_layout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MplCanvas
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class MplCanvas(FigureCanvas):
def __init__(self):
# self.x = x
self.fig = Figure()
self.fig.set_tight_layout(True)
self.ax1 = self.fig.add_subplot(211)
self.ax1.set_title("Whole Chr")
self.ax2 = self.fig.add_subplot(212)
self.ax2.set_title("Zoom in Region")
self.line2 = object()
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
示例2: PlotWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class PlotWidget(QWidget):
def __init__(self, name, plotFunction, plot_condition_function_list, plotContextFunction, parent=None):
QWidget.__init__(self, parent)
self.__name = name
self.__plotFunction = plotFunction
self.__plotContextFunction = plotContextFunction
self.__plot_conditions = plot_condition_function_list
""":type: list of functions """
self.__figure = Figure()
self.__figure.set_tight_layout(True)
self.__canvas = FigureCanvas(self.__figure)
self.__canvas.setParent(self)
self.__canvas.setFocusPolicy(Qt.StrongFocus)
self.__canvas.setFocus()
vbox = QVBoxLayout()
vbox.addWidget(self.__canvas)
self.__toolbar = NavigationToolbar(self.__canvas, self)
vbox.addWidget(self.__toolbar)
self.setLayout(vbox)
self.__dirty = True
self.__active = False
self.resetPlot()
def getFigure(self):
""" :rtype: matplotlib.figure.Figure"""
return self.__figure
def resetPlot(self):
self.__figure.clear()
def updatePlot(self):
if self.isDirty() and self.isActive():
print("Drawing: %s" % self.__name)
self.resetPlot()
plot_context = self.__plotContextFunction(self.getFigure())
self.__plotFunction(plot_context)
self.__canvas.draw()
self.setDirty(False)
def setDirty(self, dirty=True):
self.__dirty = dirty
def isDirty(self):
return self.__dirty
def setActive(self, active=True):
self.__active = active
def isActive(self):
return self.__active
def canPlotKey(self, key):
return any([plotConditionFunction(key) for plotConditionFunction in self.__plot_conditions])
示例3: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
def __init__(self, parent=None, width=5, height=5, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
fig.set_tight_layout({"pad": 1})
self.axes = fig.add_subplot(111)
self.plot_data = None
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
示例4: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
def __init__(self, parent=None, width=5, height=5, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
fig.set_facecolor("#282828")
fig.set_tight_layout({"pad": 1})
self.axes = fig.add_subplot(111)
self.plot_data = [[[0], [0]], [datetime.datetime.now()]]
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.compute_initial_figure()
示例5: _plot
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
def _plot(self, channel, title, data, classes):
fig = Figure(facecolor="white")
ax = fig.add_subplot(111)
class_names = [v.name for v in classes.values()]
colors = [v.color.name() for v in classes.values()]
names = sorted(data.keys())
w1 = 1.0/(len(data) + 2)
ind = np.arange(len(classes))
legendbars = list()
ticks = list()
tick_labels = list()
for i, tn in enumerate(names):
# ensure to have it ordered
values = [data[tn][cn] for cn in class_names]
wprops = dict(color="black")
bprops = dict(color="black")
bp = ax.boxplot(values, positions=(ind + i*w1), widths=0.75*w1,
whiskerprops=wprops, boxprops=bprops)
bars = self.autoColor(ax, bp, tn, colors)
ticks.extend(ind + i*w1)
tick_labels.extend([tn]*len(class_names))
ax.set_ylabel("%s (arb.)" %title)
ax.set_title("%s" %channel)
ax.set_xticks(ticks)
if len(data) >= 2:
ax.set_xticklabels(tick_labels, rotation=90)
else:
ax.set_xticklabels([""]*len(class_names))
ax.set_xlim((min(ticks) - w1, max(ticks) + w1))
yr = np.array(ax.get_ylim())
yr = yr+np.array((-1, 1))*0.1*yr.ptp()
ax.set_ylim(yr)
ax.legend(bars, class_names, frameon=False, fontsize=10, loc=2, ncol=10)
fig.set_tight_layout(True)
self.addFigure(channel, fig)
示例6: _plot
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
def _plot(self, class_counts, treatments, classes):
fig = Figure(facecolor="white")
ax = fig.add_subplot(111)
class_names = [v.name for v in classes.values()]
colors = [v.color.name() for v in classes.values()]
names = sorted(treatments.keys())
w1 = 1.0/(len(treatments) + 2)
ind = np.arange(len(classes))
ticks = list()
tick_labels = list()
for i, tn in enumerate(names):
# ensure to have it oredered
values = [treatments[tn][cn] for cn in class_names]
bars = ax.bar(ind + i*w1, values, w1, color=colors)
ticks.extend(ind + (i + 0.5)*w1)
tick_labels.extend([tn]*len(class_names))
autolabel(ax, bars)
ax.set_ylabel('counts')
ax.set_xticks(ticks)
shift = 0.5*(max(len(treatments), 2))*w1
if len(treatments) >= 2:
ax.set_xlim((ind.min()- 0.5*shift, ind.max()+ 2.5*shift))
ax.set_xticklabels(tick_labels, rotation=90)
else:
ax.set_xticklabels([""]*len(class_names))
ax.set_xlim((ind.min()- 0.5*shift, ind.max()+ 1.5*shift))
yr = np.array(ax.get_ylim())
yr = yr+np.array((0, 1))*0.1*yr.ptp()
ax.set_ylim(yr)
ax.legend(bars, class_names, frameon=False, fontsize=10, loc=2,
ncol=10)
fig.set_tight_layout(True)
qfw = QFigureWidget(fig, self)
self.vbox.addWidget(qfw)
示例7: MplCanvas
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class MplCanvas(FigureCanvas):
"""Class to represent the FigureCanvas widget"""
#signals
rightDrag = Signal(float, float)
leftDrag = Signal(float, float)
def __init__(self):
interactive = matplotlib.is_interactive()
matplotlib.interactive(False)
# setup Matplotlib Figure and Axis
self.fig = Figure(facecolor='#ffffff')
try:
self.fig.set_tight_layout(True)
except AttributeError: # matplotlib < 1.1
pass
# initialization of the canvas
FigureCanvas.__init__(self, self.fig)
# we define the widget as expandable
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
# notify the system of updated policy
FigureCanvas.updateGeometry(self)
self.manager = FigureManager(self, 0)
matplotlib.interactive(interactive)
def paintEvent(self, event):
#draw the zoom rectangle more prominently
drawRect = self.drawRect
self.drawRect = False
super(MplCanvas, self).paintEvent(event)
if drawRect:
p = QtGui.QPainter(self)
p.setPen(QtGui.QPen(Qt.red, 2, Qt.DotLine))
p.drawRect(self.rect[0], self.rect[1], self.rect[2], self.rect[3])
p.end()
示例8: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class Gui:
def __init__( self ):
self.root = tk.Tk()
self.root.wm_title( "Log grapher" )
matplotlib.rc('font', size=8 )
self.fig = Figure( figsize=(11,5), dpi=100 )
self.fig.set_tight_layout( True )
self.axis = self.fig.add_subplot( 111 )
self.axis.set_title( 'Graph' )
self.axis.set_xlabel( 'X axis label' )
self.axis.set_ylabel( 'Y label' )
self.canvas = FigureCanvasTkAgg( self.fig, master=self.root )
self.canvas.show()
self.canvas.get_tk_widget().pack( side=TOP, fill=BOTH, expand=1 )
def setLabels( self, labelList ):
"""setLabels before doing anything else - configures axes etc"""
self.labels = labelList
for i in range( 0, len( labelList ) ):
self.axis.plot( [] )
self.fig.legend( self.axis.lines, self.labels, 'lower center', ncol=len(self.labels),
borderpad=0.3, handletextpad=0.2, columnspacing=0.3 )
def append( self, xVal, yValList ):
"""
yValList must be the same length as labelList, None values will be ignored.
Call update() afterwards.
"""
#print( "gui append " + str( xVal ) + ", " )
#pprint( yValList )
for idx, yVal in enumerate( yValList ):
if yVal is not None:
hl = self.axis.lines[idx]
hl.set_xdata( numpy.append( hl.get_xdata(), xVal ) )
hl.set_ydata( numpy.append( hl.get_ydata(), yVal ) )
def update( self ):
self.axis.relim()
self.axis.autoscale_view()
self.canvas.draw()
示例9: MplCanvas
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class MplCanvas(FigureCanvas):
"""Class to represent the FigureCanvas widget"""
#signals
rightDrag = pyqtSignal(float, float)
leftDrag = pyqtSignal(float, float)
def __init__(self):
# setup Matplotlib Figure and Axis
self.fig = Figure(facecolor='#ffffff')
try:
self.fig.set_tight_layout(True)
except AttributeError: # matplotlib < 1.1
pass
# initialization of the canvas
FigureCanvas.__init__(self, self.fig)
# we define the widget as expandable
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
# notify the system of updated policy
FigureCanvas.updateGeometry(self)
示例10: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class Chart:
# I got the how to do this from the following website and I thank the author for the information.
# http://blog.rcnelson.com/building-a-matplotlib-gui-with-qt-designer-part-1/
''' Developer Note: Add generic container widget called mplwindow, drop any widget within mplwindow and layout
vertical then delete the temporary widget. Set the vertical layout name to mplvl
'''
def __init__(self, ui):
'''
:param ui: The UI to which we need for displaying the chart.
:param datatranslator: The data translator for access to the imported data.
:param metadata: The metadata we found when doing a csv import
:param instrument: The instrument configuration which includes the base metadata as set by the instrument xml
:param config: The application config parser.
:return:
'''
##initialise logger
logger = logging.getLogger('graphics.Chart.init')
self.ui = ui
self.data_store = None
self.data_source = None
self.instrument = None
self.metadata = None
self.application_configuration = None
self.run_once = False
mpl.rcParams['font.monospace'] = 'Courier New'
mpl.rcParams['savefig.bbox'] = 'tight'
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['axes.facecolor'] = "#FDFDF0"
mpl.rcParams['figure.max_open_warning'] = 2
mpl.rcParams['figure.facecolor'] = '#FFFFE0'
mpl.rcParams['legend.framealpha'] = 0.5
mpl.rcParams['legend.fancybox'] = True
mpl.rcParams['lines.markersize'] = 5
mpl.rcParams['figure.autolayout'] = True
mpl.rcParams['ytick.labelsize'] = 'small'
mpl.rcParams['xtick.labelsize'] = 'small'
self.fig = Figure()
self.ax1f1 = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
if mpl.get_backend().lower() in ['agg', 'macosx']:
self.fig.set_tight_layout(True)
else:
self.fig.tight_layout()
logger.info('Initialised charting.')
def chart_instrument_setup(self, datastore, instrument, metadata, application_configuration, datasource):
self.data_store = datastore
self.data_source = datasource
self.instrument = instrument
self.metadata = metadata
self.application_configuration = application_configuration
mpl.rcParams['savefig.directory'] = self.application_configuration.get('Application', 'instrument_data_path')
def add_data(self, type):
logger = logging.getLogger('graphics.Chart.add_data')
# Clear the current chart if present.
if self.ax1f1 is not None:
self.ax1f1.clear()
# print('Data source : %s' % str(self.data_store.DataSource))
# Set labels and ranges from metadata depending on data source.
if self.data_store.DataSource == 'Controller':
title = self.instrument.instrument_description
channel_names = self.instrument.channel_names
channel_colours = self.instrument.channel_colours
channel_units = self.instrument.channel_units
y_axis_label = self.instrument.YaxisLabel
x_axis_label = self.instrument.XaxisLabel
y_axis_range = self.instrument.YaxisRange
elif self.data_store.DataSource == 'CSV':
title = self.metadata.ObservationTitle
channel_names = self.metadata.channel_names
channel_colours = self.metadata.channel_colours
channel_units = self.metadata.channel_units
y_axis_label = self.metadata.YaxisLabel
x_axis_label = self.metadata.XaxisLabel
y_axis_range = None
else:
return 'PREMATURE_TERINATION', 'Unknown data source : %s' % str(self.data_source)
#.........这里部分代码省略.........
示例11: PlotWindow
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
#.........这里部分代码省略.........
self.widgets['btn_copy'] = ttk.Button(self.widgets['frame_artist_widgets'], text='Copy to clipboard')
self.widgets['btn_copy']["command"] = self.action_btn_copy
self.widgets['btn_copy'].pack(side=tk.LEFT, padx=10, pady=5)
# Zoom line button
self.widgets['btn_zoomsingle'] = ttk.Button(self.widgets['frame_artist_widgets'], text='Zoom curve')
self.widgets['btn_zoomsingle']["command"] = self.action_btn_zoomsingle
self.widgets['btn_zoomsingle'].pack(side=tk.LEFT, padx=10, pady=5)
##########################
# Bottom frame
##########################
self.widgets['bottom_frame'] = ttk.Frame(self)
#self.widgets['btn_test'] = ttk.Button(self.widgets['bottom_frame'], text='Teste')
#self.widgets['btn_test'].grid(row=0, column=0, sticky='nsew')
self.widgets['log_listbox'] = ScrollableListbox(self.widgets['bottom_frame'], height=4)
self.widgets['log_listbox'].grid(row=0, column=0, sticky='nsew')
self.widgets['bottom_frame'].grid(row=3, column=0, sticky="nsew", pady=10, padx=10)
# Elastic columns
tk.Grid.columnconfigure(self.widgets['bottom_frame'], 0, weight=1)
tk.Grid.columnconfigure(self, 0, weight=1)
tk.Grid.rowconfigure(self, 2, weight=1)
tk.Grid.rowconfigure(self, 0, weight=0)
def log(self, text):
self.widgets['log_listbox'].append(text)
self.widgets['log_listbox'].see(tk.END)
def default_config(self):
self.main_axes.get_xaxis().get_major_formatter().set_useOffset(False)
self.main_axes.get_yaxis().get_major_formatter().set_useOffset(False)
self.fig.set_tight_layout(True)
def action_btn_zoomsingle(self, *args, **kwargs):
if self.selected_artist is not None:
line = self.selected_artist['artist']
min_x = min(line.get_xdata())
max_x = max(line.get_xdata())
min_y = min(line.get_ydata())
max_y = max(line.get_ydata())
self.main_axes.set_xlim([min_x, max_x])
self.main_axes.set_ylim([min_y, max_y])
# Redraw changes
self.fig.canvas.draw()
def action_btn_export(self, *args, **kwargs):
file_path = fd.asksaveasfilename()
if file_path:
line_num = 0
for line in self.main_axes.get_lines():
line_num += 1
path = file_path + '_' + self.plot_type + '_' + str(line_num) + '.txt'
np.savetxt(path, np.column_stack([line.get_xdata(), line.get_ydata()]))
def action_btn_quick_normalization(self, *args, **kwargs):
for line in self.main_axes.get_lines():
y = line.get_ydata()
y = y-np.amin(y)
y = np.divide(y, np.amax(y))
line.set_ydata(y)
self.action_btn_zoomall()
def disable_picker(self, *args, **kwargs):
示例12: Figure
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
import serial.tools.list_ports
# from serial import *
# from Tkinter import *
arduino = serial.Serial('/dev/ttyACM0', 9600)
db = mdb.connect(charset='utf8', host="127.0.0.1", user="root", passwd="root", db="lwc_members")
cur = db.cursor()
LARGE_FONT= ("Times", 20)
style.use("ggplot")
f = Figure(figsize=(5,5), dpi=100)
f.set_tight_layout(False)
a = f.add_subplot(221)
b = f.add_subplot(222)
c = f.add_subplot(223)
d = f.add_subplot(224)
def animate(i):
'''
Animate for sunday Service attendance stats
'''
event_type = "Sunday Service"
month = 9
cur.execute("SELECT * FROM att_summ_2 WHERE event_type='%s' AND month(event_date)=%d " % (event_type, month) )
data = cur.fetchall()
示例13: MplGraphQt5Widget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class MplGraphQt5Widget(QWidget):
def __init__(self, parent=None):
super(MplGraphQt5Widget, self).__init__(parent)
self.width = 3
self.height = 3
self.dpi = 100
self._dataY = np.array([])
self._dataX = np.array([])
self._spCols = 1
self._spRows = 1
self.all_sp_axes = []
self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
self.all_sp_axes.append(self.fig.add_subplot(self._spCols, self._spRows, 1))
self.fig.set_frameon(False)
self.fig.set_tight_layout(True)
self.canvas = Canvas(self.fig)
self._navBarOn = False
self.mpl_toolbar = NavigationToolbar(self.canvas, parent)
self.mpl_toolbar.dynamic_update()
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.canvas.mpl_connect('button_press_event', self.on_button_press)
self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.canvas.setParent(parent)
self.canvas.clearMask()
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.canvas.updateGeometry()
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
if not self._navBarOn:
self.mpl_toolbar.hide()
self.setLayout(vbox)
def get_icon(name):
"""Return Matplotlib icon *name*"""
return QIcon(osp.join(rcParams['datapath'], 'images', name))
key_pressed = pyqtSignal(object, name='keyPressed')
def on_key_press(self, event):
self.key_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
button_pressed = pyqtSignal(object, name='buttonPressed')
def on_button_press(self, event):
self.button_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
mouse_move = pyqtSignal(object, name='mouseMoved')
def on_mouse_move(self, event):
self.mouse_move.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
def generateNewAxes(self):
for ax in self.all_sp_axes:
self.fig.delaxes(ax)
self.all_sp_axes = []
numOfAxes = (self._spRows*self._spCols)+1
for i in np.arange(1,numOfAxes):
self.all_sp_axes.append(self.fig.add_subplot(self._spRows, self._spCols, i))
self.canvas.setGeometry(100, 100, 300, 300) #Used to update the new number of axes
self.canvas.updateGeometry() #This will bring the size of the canvas back to the original (defined by the vbox)
spRowsChanged = pyqtSignal(int)
def getspRows(self):
return self._spRows
@pyqtSlot(int)
def setspRows(self, spRows):
self._spRows = spRows
self.generateNewAxes()
self.spRowsChanged.emit(spRows)
def resetspRows(self):
self.setspRows(1)
spRows = pyqtProperty(int, getspRows, setspRows, resetspRows)
spColsChanged = pyqtSignal(int)
def getspCols(self):
return self._spCols
#.........这里部分代码省略.........
示例14: _create_graph
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
def _create_graph(self, graph_model):
"""
Create graph with all its contents.
:param graph_model: Model describing layout from model_wrapper.
:return: Graph element.
"""
assert isinstance(graph_model, models.Graph)
widget = QtGui.QWidget()
widget_layout = QtGui.QVBoxLayout()
widget.setLayout(widget_layout)
widget.setContentsMargins(0, 0, 0, 0)
fig = Figure()
if graph_model.properties_as_dict()['projection'].get() == 'polar':
axes = fig.add_subplot(111, projection='polar')
else:
axes = fig.add_subplot(111)
axes.hold(True)
axes.set_autoscalex_on(False)
axes.set_autoscaley_on(False)
fig.set_facecolor((0.0, 0.0, 0.0, 0.0))
fig.set_tight_layout(True)
canvas = FigureCanvas(fig)
def set_title(axes_, canvas_, value):
axes_.set_title(value)
canvas_.draw_idle()
def set_grid(axes_, canvas_, value):
axes_.grid(value)
canvas_.draw_idle()
accessor_map = {
'width': (widget.width, widget.setFixedWidth),
'height': (widget.height, widget.setFixedHeight),
'title': (axes.get_title,
functools.partial(set_title, axes, canvas)),
'grid': (lambda: axes._gridOn,
functools.partial(set_grid, axes, canvas))
}
dimension_list = None
for p in graph_model.properties:
if p.property in accessor_map:
wrap_and_bind(self.binding_context, canvas, p,
*accessor_map[p.property])
for child in graph_model.children:
if isinstance(child, models.GraphDimensions):
dimension_list = self._create_graph_dimensions(child)
# or layers.
elif isinstance(child, models.GraphLayers):
self._create_graph_layers(child, axes, canvas)
# We let each layer take responsibility for managing and adding their
# own artists, hence removing code below. This is necessary since some
# plots change the number of artists depending on some property.
# One example is a 1D-histogram where the number of rectangles change
# when the number of bins change. It also simplifies being able to
# reuse existing MPL-plots which are adding the elements automatically.
self._bind_axes(dimension_list, axes, canvas, graph_model)
widget_layout.addWidget(canvas)
return widget
示例15: MyMplCanvas
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_tight_layout [as 别名]
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, streamline, parent=None, width=5, height=4, dpi=50, subs=1):
self.fig = Figure(figsize=(width - 50, height), dpi=dpi)
pos = 0
self.sl = streamline
self.subs = subs
self.cpunum = self.sl.mDevice.cpu_num
self.gpu_pos = 0
self.fps_pos = 0
self.temp_pos = 0
self.axes = []
for i in range(self.cpunum):
self.axes.append(self.fig.add_subplot(self.subs, 1, i + 1)) # For CPU CORES
# We want the axes cleared every time plot() is called
self.axes[i].set_title('CPU' + str(i))
# self.axes[i].set_xticks([]) # not show x
self.axes[i].set_xlim(0, 20000)
self.axes[i].set_ylim(0, 2500)
if self.sl.mDevice.show_gpu == 1:
self.gpu_pos = pos
self.axes.append(self.fig.add_subplot(self.subs, 1, self.cpunum + pos + 1)) # FOR GPU
self.axes[self.cpunum + self.gpu_pos].set_title('GPU')
self.axes[self.cpunum + self.gpu_pos].set_xlim(0, 20000)
self.axes[self.cpunum + self.gpu_pos].set_ylim(0, 850)
pos += 1
if self.sl.mDevice.show_fps == 1:
self.fps_pos = pos
self.axes.append(self.fig.add_subplot(self.subs, 1, self.cpunum + self.fps_pos + 1)) # FOR FPS
self.axes[self.cpunum + self.fps_pos].set_title('FPS')
self.axes[self.cpunum + self.fps_pos].set_xlim(0, 20000)
self.axes[self.cpunum + self.fps_pos].set_ylim(0, 100)
pos += 1
if self.sl.mDevice.show_temp == 1:
self.temp_pos = pos
self.axes.append(self.fig.add_subplot(self.subs, 1, self.cpunum + self.temp_pos + 1)) # FOR CPU TEMP
self.axes[self.cpunum + self.temp_pos].set_title('CPU Temperature')
self.axes[self.cpunum + self.temp_pos].set_xlim(0, 20000)
self.axes[self.cpunum + self.temp_pos].set_ylim(0, 100)
self.axes.append(self.fig.add_subplot(self.subs, 1, self.cpunum + self.temp_pos + 2)) # FOR BOARD TEMP
self.axes[self.cpunum + self.temp_pos + 1].set_title('Board Temperature')
self.axes[self.cpunum + self.temp_pos + 1].set_xlim(0, 20000)
self.axes[self.cpunum + self.temp_pos + 1].set_ylim(0, 100)
self.fig.set_tight_layout(True)
self.compute_initial_figure()
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
FigureCanvas.setFixedSize(self, width - 50, subs * 100)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def compute_initial_figure(self):
pass