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 demo_locatable_axes_hard(fig): from mpl_toolkits.axes_grid1 import SubplotDivider, Size from mpl_toolkits.axes_grid1.mpl_axes import Axes divider = SubplotDivider(fig, 2, 2, 2, aspect=True) # axes for image ax = Axes(fig, divider.get_position()) # axes for colorbar ax_cb = Axes(fig, divider.get_position()) h = [ Size.AxesX(ax), # main axes Size.Fixed(0.05), # padding, 0.1 inch Size.Fixed(0.2), # colorbar, 0.3 inch ] v = [Size.AxesY(ax)] divider.set_horizontal(h) divider.set_vertical(v) ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0)) fig.add_axes(ax) fig.add_axes(ax_cb) ax_cb.axis["left"].toggle(all=False) ax_cb.axis["right"].toggle(ticks=True) Z, extent = get_demo_image() im = ax.imshow(Z, extent=extent, interpolation="nearest") plt.colorbar(im, cax=ax_cb) plt.setp(ax_cb.get_yticklabels(), visible=False)
def clearplot(self): utils.trace('in') if self._plot is not None: if self._plot[0] == 'surface': self._plot[1].remove() figure = self._plot[3] if len(figure.axes) > 1: figure.delaxes(figure.axes[1]) ax = self._earthplot._axes cbax = self._earthplot._clrbar_axes divider = make_axes_locatable(ax) divider.set_horizontal( [Size.AxesX(ax), Size.Fixed(0), Size.Fixed(0)]) elif self._plot[0] == 'contour': for element in self._plot[1].collections: try: element.remove() except ValueError: print(element) if len(self._plot) > 2: try: self._plot[2][0].remove() except TypeError: print("None element cannot be removed") try: self._plot[3].remove() except AttributeError: print("None element have no attribute remove") for element in self._plot[4]: element.remove() self._plot = None utils.trace('out')
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 __init__(self, nrows=1, ncols=1, n_axes=1, penal_width=2.5, penal_height=2, p=0.6, figsize=(8.27, 11.69), mar_left=1, mar_bottom=1): self.nrows = nrows self.ncols = ncols self.n_axes = n_axes self.penal_width = penal_width self.penal_height = penal_height self.p = p self.figsize = figsize self.fig_width, self.fig_height = figsize self.mar_left = mar_left self.mar_bottom = mar_bottom if self.nrows > 1: self.v = divide_penal(penal_height, self.nrows, self.mar_bottom, self.p) else: self.v = [Size.Fixed(mar_bottom), Size.Fixed(penal_height)] if self.ncols > 1: self.h = divide_penal(penal_width, self.ncols, self.mar_left, self.p) else: self.h = [Size.Fixed(mar_left), Size.Fixed(penal_width)]
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 plot_it(): # fig = plt.figure(1, figsize=(8, 4.5)) fig = plt.figure(1, figsize=(16, 12)) # h = [Size.Fixed(0.), Size.Fixed(6.5)] # v = [Size.Fixed(0.5), Size.Fixed(3.25)] h = [Size.Fixed(0.), Size.Fixed(13)] v = [Size.Fixed(0.5), Size.Fixed(7)] win = Divider(fig, (0.1, 0.08, 0.8, 0.8), h, v, aspect=False) ax = Axes(fig, win.get_position()) ax.set_axes_locator(win.new_locator(nx=1, ny=1)) fig.add_axes(ax) # fig = plt.figure(figsize=(16, 12)) # ax = fig.add_subplot(111) for ii, ellipse in enumerate(ellipses): ax.fill(ellipse[0], ellipse[1], color=cmap(norm_vals[ii]), zorder=0) ax.plot(ellipse[0], ellipse[1], 'k-', linewidth=0.2) ax.invert_yaxis() plt.xlabel('Northing (km)', fontsize=16) plt.ylabel(r'$\log_{10}$ Period (s)', fontsize=16) # ax.set_aspect(1) ax.tick_params(axis='both', labelsize=14) # locs, labels = plt.xticks() # plt.xticks(locs, [int(x * 10) for x in locs]) fake_vals = np.linspace(lower, upper, len(fill_vals)) fake_im = ax.scatter(loc, periods, c=fake_vals, cmap=cmap) fake_im.set_visible(False) # ax.set_ylim([-2.6, 3.25]) # ax.set_xlim([526.5, 538.2]) # ax.invert_yaxis() # cb = plt.colorbar(mappable=fake_im) ############################################# # Colour bar and site labelling # cbaxes = fig.add_axes([0.925, 0.1351, 0.015, 0.72]) # cb = plt.colorbar(fake_im) # if 'phi' in fill_param[:3]: # label = r'${}{}(\degree)$'.format('\phi', fill_param[-2:]) # else: # label = r'$\{}(\degree)$'.format(fill_param) # cb.set_label(label, # rotation=270, # labelpad=20, # fontsize=18) # ax.tick_params(axis='both', labelsize=14) # ax.set_xlim(x_lim) # for ii, site in enumerate(main_sites): # txt = site[-4:-1] # if linear_xaxis: # ax.text(linear_site[ii], # label_offset, site, rotation=45) # 3.6 # else: # ax.text(main_transect.sites[site].locations['X'], # label_offset, site, rotation=45) # 3.6 plt.show() return fig
def addColorbar(mappable, ax): """ Append colorbar to axes Parameters ---------- mappable : a mappable object ax : an axes object Returns ------- cbax : colorbar axes object Notes ----- This is mostly useful for axes created with :func:`curvedEarthAxes`. written by Sebastien, 2013-04 """ from mpl_toolkits.axes_grid1 import SubplotDivider, LocatableAxes, Size import matplotlib.pyplot as plt fig1 = ax.get_figure() divider = SubplotDivider(fig1, *ax.get_geometry(), aspect=True) # axes for colorbar cbax = LocatableAxes(fig1, divider.get_position()) h = [ Size.AxesX(ax), # main axes Size.Fixed(0.1), # padding Size.Fixed(0.2) ] # colorbar v = [Size.AxesY(ax)] _ = divider.set_horizontal(h) _ = divider.set_vertical(v) _ = ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) _ = cbax.set_axes_locator(divider.new_locator(nx=2, ny=0)) _ = fig1.add_axes(cbax) _ = cbax.axis["left"].toggle(all=False) _ = cbax.axis["top"].toggle(all=False) _ = cbax.axis["bottom"].toggle(all=False) _ = cbax.axis["right"].toggle(ticklabels=True, label=True) _ = plt.colorbar(mappable, cax=cbax) return cbax
def init_ax(self, fig): h = [Size.Fixed(self.size_on_screen[0])] v = [Size.Fixed(self.size_on_screen[1])] self.divider = self.get_divider(fig) self.ax = fig.add_axes(self.divider.get_position(), axes_locator=self.divider.new_locator(nx=1, ny=1)) self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) self.ax.set_xlim(0, self.actual_size[0]) self.ax.set_ylim(0, self.actual_size[1])
def __init__(self, ax, cview_args={}, display_args={}, colormap=[]): cview_ax = Axes(ax.get_figure(), ax.get_position(original=True)) cmap_ax = Axes(ax.get_figure(), ax.get_position(original=True)) self.ax = ax self.cview = ColorViewer(cview_ax, **cview_args) self.colormap = MapDisplay(cmap_ax, self.cview, **display_args) for name, color in colormap: self.colormap.add_item(name, color) divider = make_axes_locatable(ax) pad = Size.Fixed(0.1) colormap_width = Size.Fraction(0.29, Size.AxesX(ax)) cview_width = Size.Fraction(0.7, Size.AxesX(ax)) divider.set_horizontal([colormap_width, pad, cview_width]) cmap_ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) ax.figure.add_axes(cmap_ax) cview_ax.set_axes_locator(divider.new_locator(nx=2, ny=0)) ax.figure.add_axes(cview_ax) ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) ax.set_axis_off()
def demo_fixed_size_axes(): fig1 = plt.figure(1, (10, 5)) # The first items are for padding and the second items are for the axes. # sizes are in inch. h = [Size.Fixed(1.0), Size.Fixed(7.5)] v = [Size.Fixed(0.7), Size.Fixed(4.5)] divider = Divider(fig1, (0.0, 0.0, 1., 1.), h, v, aspect=False) # the width and height of the rectangle is ignored. ax = LocatableAxes(fig1, divider.get_position()) ax.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig1.add_axes(ax) ax.plot([1, 2, 3])
def plot_heatmap(fig2, Z): from mpl_toolkits.axes_grid1 \ import SubplotDivider, LocatableAxes, Size Z = np.flipud(Z) divider = SubplotDivider(fig2, 1, 1, 1, aspect=True) # axes for image ax = LocatableAxes(fig2, divider.get_position()) # axes for colorbar ax_cb = LocatableAxes(fig2, divider.get_position()) h = [ Size.AxesX(ax), # main axes Size.Fixed(0.05), # padding, 0.1 inch Size.Fixed(0.2), # colorbar, 0.3 inch ] v = [Size.AxesY(ax)] divider.set_horizontal(h) divider.set_vertical(v) ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0)) fig2.add_axes(ax) fig2.add_axes(ax_cb) ax_cb.axis["left"].toggle(all=False) ax_cb.axis["right"].toggle(ticks=True) im = ax.imshow(Z, cmap=cm.coolwarm, extent=(0, 1, 0, 1), interpolation="nearest") plt.colorbar(im, cax=ax_cb) plt.setp(ax_cb.get_yticklabels(), visible=False) mngr = plt.get_current_fig_manager() geom = mngr.window.geometry() x, y, dx, dy = geom.getRect() mngr.window.setGeometry(dx + 200, 100, dx, dy)
def fix_sz_fig(width, height, width_ext=2, padding=.5): # These code is to make fixed size article # Makesure matplotlib can draw Chinese characters plt.rcParams['font.sans-serif'] = ['SimHei'] # Init figure fig = plt.figure(figsize=(width + 2 * padding + width_ext, height + 2 * padding)) # The first items are for padding and the second items are for the axes. # Article width and height w = [Size.Fixed(padding), Size.Fixed(width)] h = [Size.Fixed(padding), Size.Fixed(height)] divider = Divider(fig, (0.0, 0.0, 1., 1.), w, h, 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
def plot2dHeatMap(fig, x, y, z): '''z is a 2d grid; x and y are implicit linspaces''' from mpl_toolkits.axes_grid1 \ import SubplotDivider, LocatableAxes, Size z = np.flipud(z) divider = SubplotDivider(fig, 1, 1, 1, aspect=True) # axes for image ax = LocatableAxes(fig, divider.get_position()) # axes for colorbar ax_cb = LocatableAxes(fig, divider.get_position()) h = [ Size.AxesX(ax), # main axes Size.Fixed(0.05), # padding, 0.1 inch Size.Fixed(0.2), # colorbar, 0.3 inch ] v = [Size.AxesY(ax)] divider.set_horizontal(h) divider.set_vertical(v) ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0)) fig.add_axes(ax) fig.add_axes(ax_cb) ax_cb.axis["left"].toggle(all=False) ax_cb.axis["right"].toggle(ticks=True) im = ax.imshow(z, cmap=cm.coolwarm, extent=(0, 1, 0, 1), interpolation="nearest") plt.colorbar(im, cax=ax_cb) plt.setp(ax_cb.get_yticklabels(), visible=False) return ax
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 get_divider(self, fig): self.border = 0.1 while self.actual_size[0] < ( self.size_on_screen[0] - 2 * self.border ) and self.actual_size[1] < (self.size_on_screen[1] - 2 * self.border): self.border += 0.1 x_factor = self.actual_size[0] / (self.size_on_screen[0] - 2 * self.border) y_factor = self.actual_size[1] / (self.size_on_screen[1] - 2 * self.border) self.scale = max(x_factor, y_factor) draw_size = (self.actual_size[0] / self.scale, self.actual_size[1] / self.scale) h = [Size.Fixed(self.border), Size.Fixed(draw_size[0])] v = [Size.Fixed(self.border), Size.Fixed(draw_size[1])] return Divider( fig, (self.location_on_screen[0], self.location_on_screen[1], 1, 1), h, v, aspect=False)
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)
def add_cbar(mappable, ax): """ Append colorbar to axes Copied from DaViTPy: https://github.com/vtsuperdarn/davitpy/blob/1b578ea2491888e3d97d6e0a8bc6d8cc7c9211fb/davitpy/utils/plotUtils.py#L674 """ from mpl_toolkits.axes_grid1 import SubplotDivider, Size from mpl_toolkits.axes_grid1.mpl_axes import Axes import matplotlib.pyplot as plt fig1 = ax.get_figure() divider = SubplotDivider(fig1, *ax.get_geometry(), aspect=True) # axes for colorbar cbax = Axes(fig1, divider.get_position()) h = [ Size.AxesX(ax), # main axes Size.Fixed(0.1), # padding Size.Fixed(0.2) ] # colorbar v = [Size.AxesY(ax)] _ = divider.set_horizontal(h) _ = divider.set_vertical(v) _ = ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) _ = cbax.set_axes_locator(divider.new_locator(nx=2, ny=0)) _ = fig1.add_axes(cbax) _ = cbax.axis["left"].toggle(all=False) _ = cbax.axis["top"].toggle(all=False) _ = cbax.axis["bottom"].toggle(all=False) _ = cbax.axis["right"].toggle(ticklabels=True, label=True) _ = plt.colorbar(mappable, cax=cbax) return cbax
def demo_locatable_axes_hard(fig): from mpl_toolkits.axes_grid1 import SubplotDivider, Size from mpl_toolkits.axes_grid1.mpl_axes import Axes divider = SubplotDivider(fig, 2, 2, 2, aspect=True) # axes for image ax = fig.add_axes(divider.get_position(), axes_class=Axes) # axes for colorbar # (the label prevents Axes.add_axes from incorrectly believing that the two # axes are the same) ax_cb = fig.add_axes(divider.get_position(), axes_class=Axes, label="cb") h = [ Size.AxesX(ax), # main axes Size.Fixed(0.05), # padding, 0.1 inch Size.Fixed(0.2), # colorbar, 0.3 inch ] v = [Size.AxesY(ax)] divider.set_horizontal(h) divider.set_vertical(v) ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0)) ax_cb.axis["left"].toggle(all=False) ax_cb.axis["right"].toggle(ticks=True) Z, extent = get_demo_image() im = ax.imshow(Z, extent=extent) plt.colorbar(im, cax=ax_cb) ax_cb.yaxis.set_tick_params(labelright=False)
def _set_ax_height_to_cm(fig: Fig, ax: Ax, height: float) -> None: from mpl_toolkits.axes_grid1 import Size, Divider height /= 2.54 # cm to inches bbox = _get_ax_bbox(fig, ax) hori = [Size.Fixed(bbox.x0), Size.Fixed(bbox.width), Size.Fixed(bbox.x1)] vert = [Size.Fixed(bbox.y0), Size.Fixed(height), Size.Fixed(bbox.y1)] divider = Divider(fig, (0.0, 0.0, 1.0, 1.0), hori, vert, aspect=False) ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
def divide_penal(penal_size, n, mar=1.0, p=0.6): """ Get horizontal/vertical term for mpl_toolkits.axes_grid1.Divider :param penal_size: total size of penal in inch :param n: number of subplots on this direction (horizontal or vertical) :param mar: the extra margin on left or bottom :param p: proportion of figure rect :return: h or v, [list of Size.Fixed()] """ ax_size = penal_size / n * p interval = penal_size / n * (1 - p) divided = [ax_size, interval] * n divided[0] += mar divided = [Size.Fixed(i) for i in divided] return divided
# 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,
lstFinalAnalysis = np.array(list(map(np.log, finalAnalysis))) sumFinalAnalysis = sum(lstFinalAnalysis) sumFinalAnalysisTE = np.matmul(-np.transpose(npTE), lstFinalAnalysis) A = np.array([[ndados, sumTE], [sumTE, prodTE]]) B = np.array([[sumFinalAnalysis], [sumFinalAnalysisTE]]) invA = np.linalg.inv(A) P = np.matmul(invA, B) T2[indexValue] = (P[1][0]) for i, t in enumerate(T2): T2[i] = math.inf if t[0] == 0 else 1000 / t[0] T2Star = np.reshape(T2, (400, 400)) fig = plt.figure(figsize=(6, 6)) h = [Size.Fixed(1.0), Size.Fixed(5.)] v = [Size.Fixed(1.0), Size.Fixed(5.)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) ax = Axes(fig, divider.get_position()) ax.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(ax) plt.pcolor(np.flip(T2Star, 0), cmap=jet_combined, vmin=0, vmax=180) toc = time.perf_counter() print(f"Executed in {toc - tic:0.4f} seconds") # toggle_selector.RS = RectangleSelector(ax, line_select_callback, # drawtype='box', useblit=True, # button=[1, 3], # don't use middle button # minspanx=5, minspany=5, # spancoords='pixels', # interactive=True)
# hsv[:, :, 2] = value # rgb = colors.hsv_to_rgb(hsv) # # if use_alpha: # rgba = colors.hsv_to_rgb(hsv) # rgba = np.dstack([rgba, alpha]) # # else: # hsv[:, :, 2] = alpha.clip(min=0.2, max=value) # rgba_l = colors.hsv_to_rgb(hsv) # alpha_l = np.abs(1 - alpha).clip(min=value, max=1) # hsv[:, :, 2] = alpha_l # rgba_lr = colors.hsv_to_rgb(hsv) cmap = colors.ListedColormap(cmap, name='test1') fig = plt.figure(1, figsize=(12, 8)) h = [Size.Fixed(0.), Size.Fixed(6.5)] v = [Size.Fixed(0.5), Size.Fixed(3.25)] win = Divider(fig, (0.1, 0.1, 0.8, 0.8), h, v, aspect=False) ax = Axes(fig, win.get_position()) ax.set_axes_locator(win.new_locator(nx=1, ny=1)) fig.add_axes(ax) # fig = plt.gcf() for ii in range(1, 2): if ii == 0: to_plot = rgb title = 'Model' elif ii == 1: to_plot = rgba title = 'Model + Resolution (Transparency)' elif ii == 2: to_plot = rgba_l
def plot(self, profile, statsResults): # *** Check if there is sufficient data to generate the plot if len(statsResults.activeData) <= 0: self.emptyAxis() return features = statsResults.getColumn('Features') if len(features) > 200: QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) reply = QtGui.QMessageBox.question(self, 'Continue?', 'Profile contains ' + str(len(features)) + ' features. ' + 'It may take several seconds to generate this plot. We recommend filtering your profile first. ' + 'Do you wish to continue?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) QtGui.QApplication.instance().restoreOverrideCursor() if reply == QtGui.QMessageBox.No: self.emptyAxis() return # *** Colour of plot elements axesColour = str(self.preferences['Axes colour'].name()) group1Colour = str(self.preferences['Group colours'][profile.groupName1].name()) group2Colour = str(self.preferences['Group colours'][profile.groupName2].name()) # *** Colour of plot elements highlightColor = (0.9, 0.9, 0.9) # *** Sort data if self.sortingField == 'p-values': statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\ [statsResults.dataHeadings['pValues']], False) elif self.sortingField == 'Effect sizes': statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\ [statsResults.dataHeadings['EffectSize']], True, True, False) elif self.sortingField == 'Feature labels': statsResults.activeData = TableHelper.SortTableStrCol(statsResults.activeData,\ statsResults.dataHeadings['Features'], False) features = statsResults.getColumn('Features') # get sorted feature labels # *** Create lists for each quantity of interest if statsResults.multCompCorrection.method == 'False discovery rate': pValueTitle = 'q-value' else: pValueTitle = 'p-value' if self.bShowCorrectedPvalues: pValueLabels = statsResults.getColumnAsStr('pValuesCorrected') if statsResults.multCompCorrection.method != 'No correction': pValueTitle += ' (corrected)' else: pValueLabels = statsResults.getColumnAsStr('pValues') effectSizes = statsResults.getColumn('EffectSize') lowerCIs = statsResults.getColumn('LowerCI') upperCIs = statsResults.getColumn('UpperCI') ciTitle = ('%.3g' % (statsResults.oneMinusAlpha()*100)) + '% confidence intervals' # *** Truncate feature labels highlightedFeatures = list(self.preferences['Highlighted group features']) if self.preferences['Truncate feature names']: length = self.preferences['Length of truncated feature names'] for i in xrange(0, len(features)): if len(features[i]) > length+3: features[i] = features[i][0:length] + '...' for i in xrange(0, len(highlightedFeatures)): if len(highlightedFeatures[i]) > length+3: highlightedFeatures[i] = highlightedFeatures[i][0:length] + '...' # *** Check that there is at least one significant feature if len(features) <= 0: self.emptyAxis('No significant features') return # *** Adjust effect size for axis scale dominateInSample2 = [] percentage1 = [] percentage2 = [] for i in xrange(0, len(effectSizes)): if statsResults.bConfIntervRatio: if effectSizes[i] < 1: # mirror CI across y-axis effectSizes[i] = 1.0 / effectSizes[i] lowerCI = effectSizes[i] - (1.0 / upperCIs[i]) upperCI = (1.0 / lowerCIs[i]) - effectSizes[i] lowerCIs[i] = lowerCI upperCIs[i] = upperCI dominateInSample2.append(i) else: lowerCIs[i] = effectSizes[i] - lowerCIs[i] upperCIs[i] = upperCIs[i] - effectSizes[i] else: lowerCIs[i] = effectSizes[i] - lowerCIs[i] upperCIs[i] = upperCIs[i] - effectSizes[i] if effectSizes[i] < 0.0: dominateInSample2.append(i) # *** Set figure size if self.legendPos == 3 or self.legendPos == 4 or self.legendPos == 8: # bottom legend heightBottomLabels = 0.56 # inches else: heightBottomLabels = 0.4 # inches heightTopLabels = 0.25 plotHeight = self.figHeightPerRow*len(features) self.imageWidth = self.figWidth self.imageHeight = plotHeight + heightBottomLabels + heightTopLabels if self.imageWidth > 256 or self.imageHeight > 256: QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.emptyAxis() reply = QtGui.QMessageBox.question(self, 'Excessively large plot', 'The resulting plot is too large to display.') QtGui.QApplication.instance().restoreOverrideCursor() return self.fig.set_size_inches(self.imageWidth, self.imageHeight) # *** Determine width of y-axis labels yLabelBounds = self.yLabelExtents(features, 8) # *** Size plots which comprise the extended errorbar plot self.fig.clear() spacingBetweenPlots = 0.25 # inches widthNumSeqPlot = 1.25 # inches if self.bShowBarPlot == False: widthNumSeqPlot = 0.0 spacingBetweenPlots = 0.0 widthPvalueLabels = 0.75 # inches if self.bShowPValueLabels == False: widthPvalueLabels = 0.1 yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight heightPlotFigSpace = plotHeight / self.imageHeight xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth pValueLabelWidthFigSpace = widthPvalueLabels / self.imageWidth widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace widthErrorBarPlot = widthPlotFigSpace*self.imageWidth - widthNumSeqPlot - spacingBetweenPlots axInitAxis = self.fig.add_axes([xPlotOffsetFigSpace,yPlotOffsetFigSpace,widthPlotFigSpace,heightPlotFigSpace]) divider = make_axes_locatable(axInitAxis) divider.get_vertical()[0] = Size.Fixed(len(features)*self.figHeightPerRow) if self.bShowBarPlot == True: divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot) axErrorbar = divider.new_horizontal(widthErrorBarPlot, pad=spacingBetweenPlots, sharey=axInitAxis) self.fig.add_axes(axErrorbar) else: divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot) axErrorbar = axInitAxis # *** Plot of sequences for each subsystem if self.bShowBarPlot == True: axNumSeq = axInitAxis meanRelFreqSeqs1 = statsResults.getColumn('MeanRelFreq1') meanRelFreqSeqs2 = statsResults.getColumn('MeanRelFreq2') if self.bShowStdDev: stdDev1 = statsResults.getColumn('StdDevRelFreq1') stdDev2 = statsResults.getColumn('StdDevRelFreq2') endCapSize = self.endCapSize else: stdDev1 = [0] * len(meanRelFreqSeqs1) stdDev2 = [0] * len(meanRelFreqSeqs2) endCapSize = 0 axNumSeq.barh(np.arange(len(features))+0.0, meanRelFreqSeqs1, height = 0.3, xerr=stdDev1, color=group1Colour, ecolor='black', capsize=endCapSize) axNumSeq.barh(np.arange(len(features))-0.3, meanRelFreqSeqs2, height = 0.3, xerr=stdDev2, color=group2Colour, ecolor='black', capsize=endCapSize) for value in np.arange(-0.5, len(features)-1, 2): axNumSeq.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=-1) axNumSeq.set_xlabel('Mean proportion (%)') maxPercentage = max(max(meanRelFreqSeqs1), max(meanRelFreqSeqs2)) axNumSeq.set_xticks([0, maxPercentage]) axNumSeq.set_xlim([0, maxPercentage*1.05]) maxPercentageStr = '%.1f' % maxPercentage axNumSeq.set_xticklabels(['0.0', maxPercentageStr]) axNumSeq.set_yticks(np.arange(len(features))) axNumSeq.set_yticklabels(features) axNumSeq.set_ylim([-1, len(features)]) for label in axNumSeq.get_yticklabels(): if label.get_text() in highlightedFeatures: label.set_color('red') for a in axNumSeq.yaxis.majorTicks: a.tick1On=False a.tick2On=False for a in axNumSeq.xaxis.majorTicks: a.tick1On=True a.tick2On=False for line in axNumSeq.yaxis.get_ticklines(): line.set_color(axesColour) for line in axNumSeq.xaxis.get_ticklines(): line.set_color(axesColour) for loc, spine in axNumSeq.spines.iteritems(): if loc in ['left', 'right','top']: spine.set_color('none') else: spine.set_color(axesColour) # *** Plot confidence intervals for each subsystem lastAxes = axErrorbar markerSize = math.sqrt(float(self.markerSize)) axErrorbar.errorbar(effectSizes, np.arange(len(features)), xerr=[lowerCIs,upperCIs], fmt='o', ms=markerSize, mfc=group1Colour, mec='black', ecolor='black', zorder=10) effectSizesSample2 = [effectSizes[value] for value in dominateInSample2] axErrorbar.plot(effectSizesSample2, dominateInSample2, ls='', marker='o', ms=markerSize, mfc=group2Colour, mec='black', zorder=100) if statsResults.bConfIntervRatio: axErrorbar.vlines(1, -1, len(features), linestyle='dashed', color=axesColour) else: axErrorbar.vlines(0, -1, len(features), linestyle='dashed', color=axesColour) for value in np.arange(-0.5, len(features)-1, 2): axErrorbar.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1) axErrorbar.set_title(ciTitle) axErrorbar.set_xlabel('Difference in mean proportions (%)') if self.bCustomLimits: axErrorbar.set_xlim([self.minX, self.maxX]) else: self.minX, self.maxX = axErrorbar.get_xlim() if self.bShowBarPlot == False: axErrorbar.set_yticks(np.arange(len(features))) axErrorbar.set_yticklabels(features) axErrorbar.set_ylim([-1, len(features)]) for label in axErrorbar.get_yticklabels(): if label.get_text() in self.preferences['Highlighted group features']: label.set_color('red') else: for label in axErrorbar.get_yticklabels(): label.set_visible(False) for a in axErrorbar.yaxis.majorTicks: a.set_visible(False) for a in axErrorbar.xaxis.majorTicks: a.tick1On=True a.tick2On=False for a in axErrorbar.yaxis.majorTicks: a.tick1On=False a.tick2On=False for line in axErrorbar.yaxis.get_ticklines(): line.set_visible(False) for line in axErrorbar.xaxis.get_ticklines(): line.set_color(axesColour) for loc, spine in axErrorbar.spines.iteritems(): if loc in ['left','right','top']: spine.set_color('none') else: spine.set_color(axesColour) # *** Show p-values on right of last plot if self.bShowPValueLabels == True: axRight = lastAxes.twinx() axRight.set_yticks(np.arange(len(pValueLabels))) axRight.set_yticklabels(pValueLabels) axRight.set_ylim([-1, len(pValueLabels)]) axRight.set_ylabel(pValueTitle) for a in axRight.yaxis.majorTicks: a.tick1On=False a.tick2On=False for loc, spine in axRight.spines.iteritems(): spine.set_color('none') # *** Legend if self.legendPos != -1: legend1 = Rectangle((0, 0), 1, 1, fc=group1Colour) legend2 = Rectangle((0, 0), 1, 1, fc=group2Colour) legend = self.fig.legend([legend1, legend2], (profile.groupName1, profile.groupName2), loc=self.legendPos, ncol=2) legend.get_frame().set_linewidth(0) #self.updateGeometry() self.draw()
var_p = var_p[unique_cells] # eliminate any nans no_nans = np.logical_or(np.isnan(x), np.isnan(y)) == 0 x = x[no_nans] y = y[no_nans] var_p = var_p[no_nans] all_cell_p = all_cell_p[no_nans] all_dVm = all_dVm[no_nans] # make the scatter s_cell = 20 #fig, ax = plt.subplots(1, 1, figsize=[1.75, 1.75]) # create a figure with axes of defined size fig = plt.figure(figsize=[2.5, 2.5]) # The first items are for padding and the second items are for the axes. # sizes are in inch. h = [Size.Fixed(0.75), Size.Fixed(1.4)] v = [Size.Fixed(0.75), Size.Fixed(1.4)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) ax = Axes(fig, divider.get_position()) ax.set_axes_locator(divider.new_locator(nx=1, ny=1)) fig.add_axes(ax) ax.scatter(x[all_cell_p < 0.05], y[all_cell_p < 0.05], s=10, facecolors='none', edgecolors=c_hyp, zorder=3) ax.scatter(x[(all_cell_p < 0.05) & (var_p < 0.05)], y[(all_cell_p < 0.05) & (var_p < 0.05)], s=s_cell, facecolors=c_hyp,
def plot_stratigraphy(section, style, ncols=1, linewidth=1, col_spacings=0.5, col_widths=1): """ Initialize a figure and subplots, with the stratigraphic section already plotted on the first axis. This function is intended to act similar to `plt.subplots()` in that it will initialize the figure and axis handles. However, given that controlling the exact width and height of the axes is critical, this function is necessary to initialize the handles correctly. Note that setting the figsize itself is not sufficient to control the width and height of the axes exactly, since the figsize includes the size of the padding around the axes. Parameters ---------- section : Section A Section object. style : Style A Style object. ncols : int The number of axes that will be in the figure (including the axis with the stratigraphic section.) linewidth : float The linewidth when drawing the stratigraphic section. col_spacings : float or array_like The spacing between the axes in inches. If a float, this value will be interpreted as uniform spacing between the axes. If an array, the length of the array must be ncols - 1, and the values will be the spacing between the individual axes. col_widths : float or array_like The width of the axes as a ratio relative to the width of the stratigraphic column. If a float, this value will be interpreted as a uniform width of the axes, excluding the stratigraphic column, for which the width is explicitly set in the Style. If an array, the length of the array must be ncols - 1, and the values will be the widths of the individual axes excluding the stratigraphic column. Returns ------- fig : matplotlib Figure Figure handle. ax : matplotlib Axes Axis handle. """ # get the attributes - implicitly checks if the attributes exist color_attribute = getattr(section, style.color_attribute) width_attribute = getattr(section, style.width_attribute) # initialize fig, ax = plt.subplots(nrows=1, ncols=ncols, sharey=True) # get the first axis if ncols == 1: ax0 = ax else: ax0 = ax[0] # determine the axis height and limits first ax_height = style.height_scaling_factor * section.total_thickness ax0.set_ylim(0, section.total_thickness) # initiate counting of the stratigraphic height strat_height = 0.0 # loop over elements of the data for i in range(section.n_units): # pull out the thickness this_thickness = section.thicknesses[i] # loop over the elements in Style to get the color and width for j in range(style.n_color_labels): if color_attribute[i] == style.color_labels[j]: this_color = style.color_values[j] for j in range(style.n_width_labels): if width_attribute[i] == style.width_labels[j]: this_width = style.width_values[j] # create the rectangle ax0.add_patch( Rectangle((0.0, strat_height), this_width, this_thickness, facecolor=this_color, edgecolor='k', linewidth=linewidth)) # count the stratigraphic height strat_height = strat_height + this_thickness # set the axis dimensions (values below are all in inches) ax0_lower_left_x = 0.5 ax0_lower_left_y = 0.5 ax0_width = style.width_inches h = [Size.Fixed(ax0_lower_left_x), Size.Fixed(ax0_width)] v = [Size.Fixed(ax0_lower_left_y), Size.Fixed(ax_height)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) ax0.set_axes_locator(divider.new_locator(nx=1, ny=1)) # prettify ax0.set_xlim(0, 1) ax0.set_xticks([0, 0.2, 0.4, 0.6, 0.8, 1]) for label in ax0.get_xticklabels(): label.set_rotation(270) label.set_ha('center') label.set_va('top') ax0.set_axisbelow(True) ax0.xaxis.grid(ls='--') ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.set_ylabel('stratigraphic height [m]') # turning the spines off creates some clipping mask issues # so just turn the clipping masks off for obj in ax0.findobj(): obj.set_clip_on(False) # check if the col_spacing and col_widths is of the correct format if type(col_spacings) == list or type(col_spacings) == np.ndarray: if len(col_spacings) != ncols - 1: raise Exception('col_spacings must be either a float or ' 'array_like with length ncols-1.') if type(col_widths) == list or type(col_widths) == np.ndarray: if len(col_widths) != ncols - 1: raise Exception('col_widths must be either a float or ' 'array_like with length ncols-1.') # set up the other axes if ncols != 1: # iterate through the axes for i in range(1, ncols): # get the spacing and width values if type(col_spacings) == list or type(col_spacings) == np.ndarray: col_spacing = col_spacings[i - 1] else: col_spacing = col_spacings if type(col_widths) == list or type(col_widths) == np.ndarray: col_width = col_widths[i - 1] * ax0_width else: col_width = col_widths * ax0_width # adjust the axis if i == 1: axn_lower_left_x = ax0_lower_left_x + ax0_width + col_spacing else: axn_lower_left_x = axn_lower_left_x + axn_width + col_spacing axn_lower_left_y = ax0_lower_left_y axn_width = col_width h = [Size.Fixed(axn_lower_left_x), Size.Fixed(axn_width)] v = [Size.Fixed(axn_lower_left_y), Size.Fixed(ax_height)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) ax[i].set_axes_locator(divider.new_locator(nx=1, ny=1)) # set the figsize here too to account for the axis size manipulation if ncols != 1: fig.set_size_inches( ax0_lower_left_x * 2 + np.sum(col_spacings) + np.sum(col_widths) + ax0_width, ax0_lower_left_y * 2 + ax_height) else: fig.set_size_inches(ax0_lower_left_x * 2 + ax0_width, ax0_lower_left_y * 2 + ax_height) return fig, ax
def plot_legend(self, legend_unit_height=0.25): """ Plot a legend for this Style object. If the color and width labels are the same, a single legend will be created. Otherwise, two legends will be created - one with the color labels, and the other with the width labels. Parameters ---------- legend_unit_height : float A scaling factor to modify the height of each unit in the legend only. Returns ------- fig : matplotlib Figure Figure handle. ax : matplotlib Axes Axis handle. """ # print some plotting values print('stratigraphic height scaling : 1 distance unit = 1 inch * {}'. format(self.height_scaling_factor)) print('width value of 1 will be : {} inches'.format( self.width_inches)) # extract attributes color_labels = self.color_labels width_labels = self.width_labels color_values = self.color_values width_values = self.width_values # if the color and width labels are different if np.any(~(color_labels == width_labels)): # sort the widths width_sort_inds = np.argsort(width_values) width_labels = width_labels[width_sort_inds] width_values = width_values[width_sort_inds] # initialize the figure fig, ax = plt.subplots(nrows=1, ncols=2, sharey=True) # determine the axis height and limits first if self.n_color_labels > self.n_width_labels: ax_height = legend_unit_height * self.n_color_labels ax[0].set_ylim(0, self.n_color_labels) ax[1].set_ylim(0, self.n_color_labels) else: ax_height = legend_unit_height * self.n_width_labels ax[0].set_ylim(0, self.n_width_labels) ax[1].set_ylim(0, self.n_width_labels) # plot the colors strat_height_colors = 0 for i in range(len(color_labels)): # create the rectangle - with thickness of 1 ax[0].add_patch( Rectangle((0.0, strat_height_colors), 1, 1, facecolor=color_values[i], edgecolor='k')) # label the unit ax[0].text(1.2, strat_height_colors + 0.5, color_labels[i], horizontalalignment='left', verticalalignment='center') # count the height strat_height_colors = strat_height_colors + 1 # set the axis dimensions (values below are all in inches) ax0_lower_left_x = 0.5 ax0_lower_left_y = 0.5 ax0_width = 0.5 h = [Size.Fixed(ax0_lower_left_x), Size.Fixed(ax0_width)] v = [Size.Fixed(ax0_lower_left_y), Size.Fixed(ax_height)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) ax[0].set_axes_locator(divider.new_locator(nx=1, ny=1)) # set the limits ax[0].set_xlim(0, 1) # prettify ax[0].set_xticks([]) ax[0].set_yticklabels([]) ax[0].set_yticks([]) # plot the widths strat_height_widths = 0 for i in range(len(width_labels)): # create the rectangle ax[1].add_patch( Rectangle((0.0, strat_height_widths), width_values[i], 1, facecolor='grey', edgecolor='k')) # the label ax[1].text(1.1, strat_height_widths + 0.5, width_labels[i], horizontalalignment='left', verticalalignment='center') # count the height strat_height_widths = strat_height_widths + 1 # set the axis dimensions (values below are all in inches) ax1_lower_left_x = ax0_lower_left_x + ax0_width + 2 ax1_lower_left_y = ax0_lower_left_y ax1_width = self.width_inches h = [Size.Fixed(ax1_lower_left_x), Size.Fixed(ax1_width)] v = [Size.Fixed(ax1_lower_left_y), Size.Fixed(ax_height)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) ax[1].set_axes_locator(divider.new_locator(nx=1, ny=1)) # prettify ax[1].set_xlim(0, 1) ax[1].set_xticks([0, 0.2, 0.4, 0.6, 0.8, 1]) for label in ax[1].get_xticklabels(): label.set_rotation(270) label.set_ha('center') label.set_va('top') ax[1].set_axisbelow(True) ax[1].xaxis.grid(ls='--') ax[1].set_yticklabels([]) ax[1].set_yticks([]) ax[1].spines['top'].set_visible(False) ax[1].spines['right'].set_visible(False) # turning the spines off creates some clipping mask issues # so just turn the clipping masks off for obj in fig.findobj(): obj.set_clip_on(False) # not really necessary since the axis sizes are already # forced, but we may as well set the figsize here too fig.set_size_inches( ax1_lower_left_x + ax1_width + ax0_lower_left_x, ax1_lower_left_y * 2 + ax_height) # if the color and width labels are the same else: # sort by width width_sort_inds = np.argsort(width_values) color_labels = color_labels[width_sort_inds] width_labels = width_labels[width_sort_inds] color_values = color_values[width_sort_inds] width_values = width_values[width_sort_inds] # initiate fig and ax fig, ax = plt.subplots() # determine the axis height and limits first ax_height = legend_unit_height * self.n_color_labels ax.set_ylim(0, self.n_color_labels) # initiate counting of the stratigraphic height strat_height = 0 # loop over each item for i in range(len(color_labels)): # create the rectangle - with thickness of 1 ax.add_patch( Rectangle((0.0, strat_height), width_values[i], 1, facecolor=color_values[i], edgecolor='k')) # label the unit ax.text(1.1, strat_height + 0.5, color_labels[i], horizontalalignment='left', verticalalignment='center') # count the stratigraphic height strat_height = strat_height + 1 # set the axis dimensions (values below are all in inches) ax_lower_left_x = 0.5 ax_lower_left_y = 0.5 ax_width = self.width_inches h = [Size.Fixed(ax_lower_left_x), Size.Fixed(ax_width)] v = [Size.Fixed(ax_lower_left_y), Size.Fixed(ax_height)] divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False) ax.set_axes_locator(divider.new_locator(nx=1, ny=1)) # prettify ax.set_xlim(0, 1) ax.set_xticks([0, 0.2, 0.4, 0.6, 0.8, 1]) for label in ax.get_xticklabels(): label.set_rotation(270) label.set_ha('center') label.set_va('top') ax.set_axisbelow(True) ax.xaxis.grid(ls='--') ax.set_yticklabels([]) ax.set_yticks([]) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # turning the spines off creates some clipping mask issues # so just turn the clipping masks off for obj in fig.findobj(): obj.set_clip_on(False) # not really necessary since the axis sizes are already # forced, but we may as well set the figsize here too fig.set_size_inches(ax_lower_left_x * 2 + ax_width, ax_lower_left_y * 2 + ax_height) return fig, ax