def demo_fixed_pad_axes(): fig = plt.figure(2, (6, 6)) # The first & third items are for padding and the second items are for the axes. # sizes are in inch. h = [ Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2), ] v = [ Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5), ] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) # the width and height of the rectangle is ignored. ax = LocatableAxes(fig, divider.get_position()) ax.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(ax) ax.plot([1, 2, 3])
def metric_svg(self, host=None, title="undefined", ylabel="undefined", metrics=[], b64encode=True): fig = pyplot.figure(figsize=self.FIGSIZE) h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) plt = Axes(fig, divider.get_position()) plt.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(plt) result = self.result runinfo = result.runinfo # ---- # The X limits are -rampupMins, runMins # ---- plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins'])) plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1) # ---- # Draw all the requested graphs # ---- x = None for m in metrics: if x is None: x, y = self._get_metric_tree(m) else: _, y = self._get_metric_tree(m, x) plt.plot(x, y, m['color'], label=m['label']) # ---- # Title and labels # ---- plt.set_title(title) plt.set_xlabel("Elapsed Minutes") plt.set_ylabel(ylabel) plt.legend(loc='upper left') plt.grid() # ---- # Now turn this into an in-memory SVG and return it as requested # (raw or b64-encoded) # ---- buf = io.StringIO() pyplot.savefig(buf, format='svg') if not b64encode: return buf.getvalue() return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
def set_divider_v_margin(self, v_margin): v = [ Size.Fixed(v_margin[0]), Size.Scaled(1.0), Size.Fixed(v_margin[1]) ] self._divider.set_vertical(v)
def set_divider_h_margin(self, h_margin): h = [ Size.Fixed(h_margin[0]), Size.Scaled(1.0), Size.Fixed(h_margin[1]) ] self._divider.set_horizontal(h)
def __init__(self, parent, file_dialog_service, cbar_height=0.2, v_gap=0.6, cbar_width=0.2, h_gap=0.6, position='bottom', **kwargs): # First element of the tuple correspond to the nx_default or ny_default. # The second element is the nx and ny position for _colorbar_axes. self._nx = { 'bottom': (1, 1), 'top': (1, 1), 'right': (1, 3), 'left': (4, 1) } self._ny = { 'bottom': (3, 1), 'top': (1, 3), 'right': (1, 1), 'left': (1, 1) } super().__init__( parent, file_dialog_service, v_axes=[Size.Scaled(1.0)] if not _is_horizontal(position) else _define_axes(position, cbar_height, v_gap), h_axes=[Size.Scaled(1.0)] if _is_horizontal(position) else _define_axes(position, cbar_width, h_gap), nx_default=self._nx[position][0], ny_default=self._ny[position][0], **kwargs) self._colorbar_axes = LocatableAxes(self._figure, self._divider.get_position()) self._colorbar_axes.set_axes_locator( self._divider.new_locator(nx=self._nx[position][1], ny=self._ny[position][1])) self._figure.add_axes(self._colorbar_axes) self._cbar = None self._points = None self._position = position
def create_plot(two_sided=False, colors=[ '#6F4C9B', '#5568B8', '#4D8AC6', '#60AB9E', '#77B77D', '#A6BE54', '#D1B541', '#E49C39', '#DF4828', '#990D38' ], markers=['o', 'v', '^', 's', 'D', '*'], figsize=(5, 3.4)): """ Crée un environnement de plot Parameters ---------- twosided : bool allows to change the size of the figure accordingly. colors : list of strings a default list exists but this allows to change it if u want markers : list of strings a default list of markers exists, but u can change it if needed Returns ------- fig, ax : matplotlib objects to be used as normal """ color = cycle(colors) marker = cycle(markers) if two_sided: fig = plt.figure(figsize=(3.4, 3.4)) else: fig = plt.figure(figsize=figsize) # The first & third items are for padding and the second items are for the # axes. Sizes are in inches. h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) # the width and height of the rectangle is ignored. ax = Axes(fig, divider.get_position()) ax.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(ax) return fig, ax, color, marker
def _define_axes(position, cbar_size, _gap): if position == 'bottom': return [Size.Fixed(cbar_size), Size.Fixed(_gap), Size.Scaled(1.0)] elif position == 'top': return [Size.Scaled(1.0), Size.Fixed(_gap), Size.Fixed(cbar_size)] elif position == 'left': return [ Size.Fixed(_gap / 4), Size.Fixed(cbar_size), Size.Fixed(_gap * 3), Size.Scaled(1.0) ] elif position == 'right': return [ Size.Scaled(1.0), Size.Fixed(_gap), Size.Fixed(cbar_size), Size.Fixed(_gap) ] else: return None
def set_size3(ax, w, h): # https://newbedev.com/axes-class-set-explicitly-size-width-height-of-axes-in-given-units from mpl_toolkits.axes_grid1 import Divider, Size axew = w / 2.54 axeh = h / 2.54 # lets use the tight layout function to get a good padding size for our axes labels. # fig = plt.gcf() # ax = plt.gca() fig = ax.get_figure() fig.tight_layout() # obtain the current ratio values for padding and fix size oldw, oldh = fig.get_size_inches() l = ax.figure.subplotpars.left r = ax.figure.subplotpars.right t = ax.figure.subplotpars.top b = ax.figure.subplotpars.bottom # work out what the new ratio values for padding are, and the new fig size. # ps: adding a bit to neww and newh gives more padding # the axis size is set from axew and axeh neww = axew + oldw * (1 - r + l) + 0.4 newh = axeh + oldh * (1 - t + b) + 0.4 newr = r * oldw / neww - 0.4 newl = l * oldw / neww + 0.4 newt = t * oldh / newh - 0.4 newb = b * oldh / newh + 0.4 # right(top) padding, fixed axes size, left(bottom) pading hori = [Size.Scaled(newr), Size.Fixed(axew), Size.Scaled(newl)] vert = [Size.Scaled(newt), Size.Fixed(axeh), Size.Scaled(newb)] divider = Divider(fig, (0.0, 0.0, 1.0, 1.0), hori, vert, aspect=False) # the width and height of the rectangle is ignored. ax.set_axes_locator(divider.new_locator(nx=1, ny=1)) # we need to resize the figure now, as we have may have made our axes bigger than in. fig.set_size_inches(neww, newh)
ax1 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=0)) label_axes(ax1, "nx=0, ny=0") ax2 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=2)) label_axes(ax2, "nx=0, ny=2") ax3 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, ny=2)) label_axes(ax3, "nx=2, ny=2") ax4 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, nx1=4, ny=0)) label_axes(ax4, "nx=2, nx1=4, ny=0") ############################################################################## # Axes sizes that scale with the figure size; fixed paddings. fig = plt.figure(figsize=(6, 6)) fig.suptitle("Scalable axes sizes, fixed paddings") horiz = [Size.Scaled(1.5), Size.Fixed(.5), Size.Scaled(1.), Size.Scaled(.5)] vert = [Size.Scaled(1.), Size.Fixed(.5), Size.Scaled(1.5)] rect = (0.1, 0.1, 0.8, 0.8) # Divide the axes rectangle into a grid with sizes specified by horiz * vert. div = Divider(fig, rect, horiz, vert, aspect=False) # The rect parameter will actually be ignored and overridden by axes_locator. ax1 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=0)) label_axes(ax1, "nx=0, ny=0") ax2 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=2)) label_axes(ax2, "nx=0, ny=2") ax3 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, ny=2)) label_axes(ax3, "nx=2, ny=2") ax4 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, nx1=4, ny=0)) label_axes(ax4, "nx=2, nx1=4, ny=0")
def __init__(self, parent, file_dialog_service, h_margin=(0.8, 0.1), v_margin=(0.5, 0.15), h_axes=[Size.Scaled(1.0)], v_axes=[Size.Scaled(1.0)], nx_default=1, ny_default=1): QWidget.__init__(self, parent) self._file_dialog_service = file_dialog_service self._figure = Figure() self._canvas = FigureCanvas(self._figure) h = [Size.Fixed(h_margin[0]), *h_axes, Size.Fixed(h_margin[1])] v = [Size.Fixed(v_margin[0]), *v_axes, Size.Fixed(v_margin[1])] self._divider = Divider(self._figure, (0.0, 0.0, 1.0, 1.0), h, v, aspect=False) self._axes = LocatableAxes(self._figure, self._divider.get_position()) self._axes.set_axes_locator( self._divider.new_locator(nx=nx_default, ny=ny_default)) self._axes.set_zorder(2) self._axes.patch.set_visible(False) for spine in ['top', 'right']: self._axes.spines[spine].set_visible(False) self._figure.add_axes(self._axes) self._canvas.setParent(self) self._layout = QVBoxLayout(self) self._layout.setContentsMargins(0, 0, 0, 0) self._layout.addWidget(self._canvas) self.setLayout(self._layout) self._figure.canvas.mpl_connect('scroll_event', self._on_scroll) self._xy_extents = None self._background_cache = None self._decoration_artists = [] self._is_panning = False self._zoom_selector = _RectangleSelector(self._axes, self._zoom_selected) self._zoom_selector.set_active(False) self._x_extent_padding = 0.01 self._y_extent_padding = 0.01 self._axes.ticklabel_format(style='sci', axis='x', scilimits=(-4, 4)) self._axes.ticklabel_format(style='sci', axis='y', scilimits=(-4, 4)) self._active_tools = {} self._span = _SpanSeletor(self._axes, self._handle_span_select, 'horizontal', rectprops=dict(alpha=0.2, facecolor='red', edgecolor='k'), span_stays=True) self._span.set_on_select_none(self._handle_span_select_none) self.span = self._previous_span = None self._span_center_mouse_event = None self._span_left_mouse_event = None self._span_right_mouse_event = None self._figure.canvas.mpl_connect('button_press_event', self._handle_press) self._figure.canvas.mpl_connect('motion_notify_event', self._handle_move) self._figure.canvas.mpl_connect('button_release_event', self._handle_release) self._figure.canvas.mpl_connect('resize_event', self._handle_resize) self.activateTool(ToolType.span, self.isActiveDefault(ToolType.span)) self._pan_event = None self._pending_draw = None self._pending_artists_draw = None self._other_draw_events = [] self._draw_timer = QTimer(self) self._draw_timer.timeout.connect(self._do_draw_events) self._draw_timer.start(20) self._zoom_skew = None self._menu = QMenu(self) self._copy_image_action = QAction(self.tr('Copy To Clipboard'), self) self._copy_image_action.triggered.connect(self.copyToClipboard) self._copy_image_action.setShortcuts(QKeySequence.Copy) self._save_image_action = QAction(self.tr('Save As Image'), self) self._save_image_action.triggered.connect(self.saveAsImage) self._show_table_action = QAction(self.tr('Show Table'), self) self._show_table_action.triggered.connect(self.showTable) self._menu.addAction(self._copy_image_action) self._menu.addAction(self._save_image_action) self._menu.addAction(self._show_table_action) self.addAction(self._copy_image_action) self._table_view = None self._single_axis_zoom_enabled = True self._cached_label_width_height = None if hasattr(type(self), 'dataChanged'): self.dataChanged.connect(self._on_data_changed) self._options_view = None self._secondary_axes = self._secondary_y_extent = self._secondary_x_extent = None self._legend = None self._draggable_legend = None self._setting_axis_limits = False self.hasHiddenSeries = False
def delay_avg_svg(self, ttype, b64encode=True): fig = pyplot.figure(figsize=self.FIGSIZE) h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) plt = Axes(fig, divider.get_position()) plt.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(plt) result = self.result runinfo = result.runinfo # ---- # The X limits are -rampupMins, runMins # ---- plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins'])) plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1) # ---- # offset the timestamps by -rampupMins so that the graph # starts with negative minutes elapsed and switches to # positive when the measurement begins. # ---- offset = (int(runinfo['rampupMins'])) * 60.0 # ---- # ttype transaction delay. First get the timestamp # and delay numbers from the result data. # The X vector then is the sorted unique timestamps rounded # to an interval. # ---- interval = 10 data = numpy.array([[(int(tup[0] / interval) * interval - offset) / 60, tup[1], tup[5]] for tup in result.result_ttype[ttype]]) x = sorted(numpy.unique(data[:, 0])) # ---- # The Y vector is the sums of transactions delay divided by # the sums of the count, grouped by X. # ---- y = [] for ts in x: tmp = data[numpy.where(data[:, 0] == ts)] y.append(numpy.sum(tmp[:, 2]) / (numpy.sum(tmp[:, 1]) + 0.000001)) # ---- # Plot the ttype delay and add all the decorations # ---- plt.plot(x, y, 'r', label='Delay') # ---- # Now do the same aggregation for the latency # ---- data = numpy.array([[(int(tup[0] / interval) * interval - offset) / 60, tup[1], tup[2]] for tup in result.result_ttype[ttype]]) # ---- # The Y vector is similar by based on latency # ---- y = [] for ts in x: tmp = data[numpy.where(data[:, 0] == ts)] y.append(numpy.sum(tmp[:, 2]) / (numpy.sum(tmp[:, 1]) + 0.000001)) plt.plot(x, y, 'b', label='Latency') plt.set_title("{} Average Latency and Delay".format(ttype)) plt.set_xlabel("Elapsed Minutes") plt.set_ylabel("Latency/Delay in ms") plt.legend(loc='upper left') plt.grid() buf = io.StringIO() pyplot.savefig(buf, format='svg') if not b64encode: return buf.getvalue() return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
def memory_svg(self, host=None, title="Memory Usage", unit="Bytes", factor=1.0, b64encode=True): fig = pyplot.figure(figsize=self.FIGSIZE) h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) plt = Axes(fig, divider.get_position()) plt.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(plt) result = self.result runinfo = result.runinfo # ---- # The X limits are -rampupMins, runMins # ---- plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins'])) plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1) x, y_used = self._get_metric_xy({ 'host': host, 'metric': 'memory.memory-used', 'factor': factor, }) _, y_cached = self._get_metric_xy( { 'host': host, 'metric': 'memory.memory-cached', 'factor': factor, }, x) _, y_buffered = self._get_metric_xy( { 'host': host, 'metric': 'memory.memory-buffered', 'factor': factor, }, x) _, y_free = self._get_metric_xy( { 'host': host, 'metric': 'memory.memory-free', 'factor': factor, }, x) # ---- # It is possible that the mqtt based metric collector produces # CSV files with different numbers of lines. We cut all of them # to a combined minimum length. # ---- min_len = min(len(x), len(y_used), len(y_cached), len(y_buffered), len(y_free)) x = x[:min_len] y_used = y_used[:min_len] y_cached = y_cached[:min_len] y_buffered = y_buffered[:min_len] y_free = y_free[:min_len] plt.stackplot(x, y_used, y_cached, y_buffered, y_free, colors=[ 'b', 'y', 'g', 'gray', ], labels=[ 'Used', 'Cached', 'Buffered', 'Free', ]) # ---- # Title and labels # ---- plt.set_title(title) plt.set_xlabel("Elapsed Minutes") plt.set_ylabel(unit) plt.legend(loc='upper left') plt.grid() # ---- # Now turn this into an in-memory SVG and return it as requested # (raw or b64-encoded) # ---- buf = io.StringIO() pyplot.savefig(buf, format='svg') if not b64encode: return buf.getvalue() return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
def tpmc_svg(self, b64encode=True): fig = pyplot.figure(figsize=self.FIGSIZE) h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) plt = Axes(fig, divider.get_position()) plt.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(plt) result = self.result runinfo = result.runinfo # ---- # The X limits are -rampupMins, runMins # ---- plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins'])) plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1) # ---- # offset the timestamps by -rampupMins so that the graph # starts with negative minutes elapsed and switches to # positive when the measurement begins. # ---- offset = (int(runinfo['rampupMins'])) * 60.0 # ---- # NEW_ORDER transactions per minute. First get the timestamp # and number of transactions from the result data. # The X vector then is the sorted unique timestamps rounded # to an interval. # ---- interval = 10 data = numpy.array([[(int(tup[0] / interval) * interval - offset) / 60, tup[1] * (60 / interval)] for tup in result.result_ttype['NEW_ORDER']]) x = sorted(numpy.unique(data[:, 0])) # ---- # The Y vector is the sums of transactions grouped by X # ---- y = [] for ts in x: tmp = data[numpy.where(data[:, 0] == ts)] y.append(numpy.sum(tmp[:, 1])) # ---- # Plot the NOPM and add all the decorations # ---- plt.plot(x, y, 'b') plt.set_title("NEW_ORDER Transactions per Minute (tpmC)") plt.set_xlabel("Elapsed Minutes") plt.set_ylabel("tpmC") plt.grid() buf = io.StringIO() pyplot.savefig(buf, format='svg') if not b64encode: return buf.getvalue() return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
# And another.. ax3 = divider.append_axes('right', size='33%', pad=0.5) ax3.plot(t, x3) # <markdowncell> # make_axes_locatable() gives one way to handle this, by giving the append_axes() method. Another way is by creating a Divider object and giving it the layout up front. # <codecell> from mpl_toolkits.axes_grid1 import Size, Divider fig = plt.figure() ax = [fig.add_axes([0.1, 0.1, 0.8, 0.8], label='%d' % i) for i in range(3)] # Create 3 Axes to be sized later horiz = [Size.Scaled(2), Size.Fixed(0.5), Size.Scaled(3), Size.Fixed(0.01)] vert = [Size.Scaled(1), Size.Fixed(0.5), Size.Scaled(1)] div = Divider(fig, (0.1, 0.1, 0.8, 0.8), horiz, vert, aspect=False) ax[0].set_axes_locator(div.new_locator(nx=0, ny=0)) ax[1].set_axes_locator(div.new_locator(nx=2, ny=0)) ax[2].set_axes_locator(div.new_locator(nx=0, nx1=2, ny=2)) ax[0].plot(t, x1) ax[1].plot(t, x2) ax[2].plot(t, x3) # <rawcell> # One obvious application of this is for doing grid of plots with colorbars. For this use case we can go one step further and make use of the ImageGrid class.
def __init__(self, images, shape): fig = plt.figure(figsize=(10, 6)) # subplot positions h_nav = [Size.Fixed(0.5), Size.Fixed(2.5)] v_nav = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)] h_im = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)] v_im = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)] nav = Divider(fig, (0.0, 0.0, 0.2, 1.), h_nav, v_nav, aspect=False) image = Divider(fig, (0.2, 0.0, 0.8, 1.), h_im, v_im, aspect=True) image.set_anchor('C') # Toolbar menu box ax1 = LocatableAxes(fig, nav.get_position()) ax1.set_axes_locator(nav.new_locator(nx=1, ny=1)) ax1.get_xaxis().set_visible(False) ax1.get_yaxis().set_visible(False) fig.add_axes(ax1, label='toolbar') ax1.text(0.05, 0.45, "Filter", weight='heavy', transform=ax1.transAxes) # Image space ax2 = LocatableAxes(fig, image.get_position()) ax2.set_axes_locator(image.new_locator(nx=1, ny=1)) fig.add_axes(ax2, label='image_space') self.callback = ImageIndex(images, shape, fig) # Navigation ## Go to ax_text_index = plt.axes([0.59, 0.05, 0.1, 0.075]) ip = InsetPosition(ax1, [0.2, 0.84, 0.3, 0.05]) ax_text_index.set_axes_locator(ip) entry_index = TextBox(ax_text_index, 'Go to', initial="0") entry_index.on_submit(self.callback.submit_index) ## Previous ax_prev = plt.axes([0.7, 0.05, 0.075, 0.075]) ip = InsetPosition(ax1, [0.55, 0.84, 0.15, 0.05]) ax_prev.set_axes_locator(ip) bprev = Button(ax_prev, '<<') bprev.on_clicked(self.callback.prev) ## Next ax_next = plt.axes([0.81, 0.05, 0.075, 0.075]) ip = InsetPosition(ax1, [0.75, 0.84, 0.15, 0.05]) ax_next.set_axes_locator(ip) bnext = Button(ax_next, '>>') bnext.on_clicked(self.callback.next) # Bounding Boxes ax_chec = plt.axes([0.1, 0.05, 0.35, 0.075]) ip = InsetPosition(ax1, [0.05, 0.5, 0.9, 0.3]) ax_chec.set_axes_locator(ip) ax_chec.text(0.05, 0.85, "Bounding Boxes", transform=ax_chec.transAxes) check = CheckButtons(ax_chec, ('characters', 'lines'), (False, False)) check.on_clicked(self.callback.update_bboxes) # Filtering ## Image ax_text_image = plt.axes([0.1, 0.1, 0.1, 0.075]) ip = InsetPosition(ax1, [0.26, 0.38, 0.64, 0.05]) ax_text_image.set_axes_locator(ip) entry_image = TextBox(ax_text_image, 'images', initial="image_id,image_id") entry_image.on_submit(self.callback.submit_images) ## Characters ax_text_char = plt.axes([0.1, 0.2, 0.1, 0.075]) ip = InsetPosition(ax1, [0.21, 0.3, 0.69, 0.05]) ax_text_char.set_axes_locator(ip) entry_char = TextBox(ax_text_char, 'chars', initial="U+3055,U+3056") entry_char.on_submit(self.callback.submit_chars) ## Reset ax_reset = plt.axes([0., 0., 1., 1.]) ip = InsetPosition(ax1, [0.05, 0.2, 0.2, 0.05]) ax_reset.set_axes_locator(ip) breset = Button(ax_reset, 'Reset') breset.on_clicked(self.callback.reset) plt.show()
def cpu_svg(self, host=None, title="CPU Usage", ylabel="Percent", b64encode=True): fig = pyplot.figure(figsize=self.FIGSIZE) h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) plt = Axes(fig, divider.get_position()) plt.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(plt) result = self.result runinfo = result.runinfo # ---- # The X limits are -rampupMins, runMins, Y limits are 0..100 # ---- plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins'])) plt.set_ylim(0, 100) plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1) # ---- # Gather all the relevant data # ---- x, y_user = self._get_metric_xy({ 'host': host, 'metric': 'cpu.percent-user', }) _, y_sys = self._get_metric_xy( { 'host': host, 'metric': 'cpu.percent-system', }, x) _, y_wait = self._get_metric_xy( { 'host': host, 'metric': 'cpu.percent-wait', }, x) _, y_intr = self._get_metric_xy( { 'host': host, 'metric': 'cpu.percent-interrupt', }, x) _, y_softirq = self._get_metric_xy( { 'host': host, 'metric': 'cpu.percent-softirq', }, x) _, y_idle = self._get_metric_xy( { 'host': host, 'metric': 'cpu.percent-idle', }, x) # ---- # It is possible that the mqtt based metric collector produces # CSV files with different numbers of lines. We cut all of them # to a combined minimum length. # ---- min_len = min(len(x), len(y_user), len(y_sys), len(y_wait), len(y_intr), len(y_softirq), len(y_idle)) x = x[:min_len] y_user = y_user[:min_len] y_sys = y_sys[:min_len] y_wait = y_wait[:min_len] y_intr = y_intr[:min_len] y_softirq = y_softirq[:min_len] y_idle = y_idle[:min_len] # ---- # Plot the CPU usage # ---- plt.stackplot(x, y_user, y_sys, y_wait, y_intr, y_softirq, y_idle, colors=[ 'g', 'b', 'r', 'c', 'm', 'y', ], labels=[ 'User', 'System', 'Wait', 'Interrupt', 'SoftIrq', 'Idle', ]) # ---- # Title and labels # ---- plt.set_title(title) plt.set_xlabel("Elapsed Minutes") plt.set_ylabel(ylabel) plt.legend(loc='upper left') plt.grid() # ---- # Now turn this into an in-memory SVG and return it as requested # (raw or b64-encoded) # ---- buf = io.StringIO() pyplot.savefig(buf, format='svg') if not b64encode: return buf.getvalue() return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
# Extract the data from the stacked boxplot data = extract_csvs(stacked_boxplot.visualization, './data/temp/csv') level_4 = data[4] # Filters the level 4 data to CD and UC IBD_level_4 = level_4.loc[level_4['dx'].isin(["CD", "UC"])] IBD_level_4 = IBD_level_4.drop(columns=metadata_columns) IBD_level_4 = IBD_level_4.set_index('index') # Normalise the data around 0 standardised = (IBD_level_4 - IBD_level_4.mean()) / IBD_level_4.std() # sets the sizing so as much of the label can be shown as possible fig = plt.figure(figsize=(11.7, 8.27)) h = [Size.Fixed(6.), Size.Scaled(.5), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(.5), Size.Fixed(.5)] divider = Divider(fig, (0, 0, 1, 1), h, v, aspect=False) ax = fig.add_axes(divider.get_position(), axes_locator=divider.new_locator(nx=1, ny=1)) # Plots the relative frequency sns.boxplot(y="variable", x="value", data=pd.melt(standardised), showfliers=False, width=.6, ax=ax) ax.xaxis.grid(True) ax.set(ylabel="Bacteria", xlabel="Relative Abundance", title="Relative Abundance for IBD for taxa at level 4") sns.despine(trim=True, left=True) plt.savefig(out_individual_boxplot) this_experiment = { "_id": experiment_id,
# sizes are in inch. h = [Size.Fixed(1.0), Size.Fixed(4.5)] v = [Size.Fixed(0.7), Size.Fixed(5.)] divider = Divider(fig, (0, 0, 1, 1), h, v, aspect=False) # The width and height of the rectangle are ignored. ax = fig.add_axes(divider.get_position(), axes_locator=divider.new_locator(nx=1, ny=1)) ax.plot([1, 2, 3]) ############################################################################### fig = plt.figure(figsize=(6, 6)) # The first & third items are for padding and the second items are for the # axes. Sizes are in inches. h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2)] v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)] divider = Divider(fig, (0, 0, 1, 1), h, v, aspect=False) # The width and height of the rectangle are ignored. ax = fig.add_axes(divider.get_position(), axes_locator=divider.new_locator(nx=1, ny=1)) ax.plot([1, 2, 3]) plt.show()