def __init__(self, edgecolor=None, facecolor=None, linewidth=None, linestyle=None, antialiased = None, hatch = None, fill=True, **kwargs ): """ The following kwarg properties are supported %(Patch)s """ artist.Artist.__init__(self) if linewidth is None: linewidth = mpl.rcParams['patch.linewidth'] if linestyle is None: linestyle = "solid" if antialiased is None: antialiased = mpl.rcParams['patch.antialiased'] self.set_edgecolor(edgecolor) self.set_facecolor(facecolor) self.set_linewidth(linewidth) self.set_linestyle(linestyle) self.set_antialiased(antialiased) self.set_hatch(hatch) self.fill = fill self._combined_transform = transforms.IdentityTransform() if len(kwargs): artist.setp(self, **kwargs)
def __init__(self, edgecolor=None, facecolor=None, linewidth=None, antialiased = None, hatch = None, fill=1, **kwargs ): """ The following kwarg properties are supported %(Patch)s """ artist.Artist.__init__(self) if edgecolor is None: edgecolor = mpl.rcParams['patch.edgecolor'] if facecolor is None: facecolor = mpl.rcParams['patch.facecolor'] if linewidth is None: linewidth = mpl.rcParams['patch.linewidth'] if antialiased is None: antialiased = mpl.rcParams['patch.antialiased'] self._edgecolor = edgecolor self._facecolor = facecolor self._linewidth = linewidth self._antialiased = antialiased self._hatch = hatch self._combined_transform = transforms.IdentityTransform() self.fill = fill if len(kwargs): artist.setp(self, **kwargs)
def _matplotlib_week_axis_setup(self, ax, xmin, xmax, ymin, ymax): from matplotlib.dates import DayLocator, DateFormatter from matplotlib.artist import setp # X axis ax.set_xlim((xmin, xmax)) ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_major_formatter(DateFormatter("%a")) ax.xaxis.grid(True, "major") # XXX - linestyle... labels = ax.get_xticklabels() setp(labels, rotation=0, fontsize=9) for i in labels: i.set_horizontalalignment('left') # Y axis ax.set_ylim((ymin, ymax)) yrange = range(ymin, ymax + 1) yticks = [] ylabels = [] # Y tick and label generation is a bit fussy - the intent here is to generate # a reasonable set of ticks and labels for various ymax values. The logic # below works reasonably well for graph height ~100 pixels and ymax from 0 to # several thousand. tickstep = 5 # for large values, steps of 5 are odd (e.g. 35, 70, 105) if ymax > 50: tickstep = 10 if ymax > 500: tickstep = 100 tickinterval = (ymax + 9) / 10 # roughly most 10 ticks per small image if tickinterval > 1: # if step > 1, round up to nearest tickstep tickinterval = (tickinterval + tickstep - 1) / tickstep * tickstep if tickinterval <= 1: tickinterval = 1 # otherwise use step 1 (also handles zero div) labelinterval = (ymax + 2) / 3 # roughly 3 labels per small image labelinterval = (labelinterval + tickstep - 1) / tickstep * tickstep # round up to nearest tickstep labelinterval = (labelinterval + tickinterval - 1) / tickinterval * tickinterval # must be a multiple of tick interval! if labelinterval <= 0: labelinterval = tickinterval # sanity if labelinterval <= 1: labelinterval = 1 ymax_rounded = (ymax + labelinterval - 1) / labelinterval * labelinterval + tickinterval # compute actual tick positions and labels for i in range(ymin, ymax_rounded + 1, tickinterval): yticks.append(i) if (int(i) % labelinterval) == 0: ylabels.append(str(int(i))) else: ylabels.append('') ax.yaxis.set_ticks(yticks) ax.yaxis.set_ticklabels(ylabels) labels = ax.get_yticklabels() setp(labels, rotation=0, fontsize=9)
def _set_ticks_labels(ax, data, labels, positions, plot_opts): """Set ticks and labels on horizontal axis.""" # Set xticks and limits. ax.set_xlim([np.min(positions) - 0.5, np.max(positions) + 0.5]) ax.set_xticks(positions) label_fontsize = plot_opts.get('label_fontsize') label_rotation = plot_opts.get('label_rotation') if label_fontsize or label_rotation: from matplotlib.artist import setp if labels is not None: if not len(labels) == len(data): msg = "Length of `labels` should equal length of `data`." raise ValueError(msg) xticknames = ax.set_xticklabels(labels) if label_fontsize: setp(xticknames, fontsize=label_fontsize) if label_rotation: setp(xticknames, rotation=label_rotation) return
def plot_data(self): # self.dataPlotsFigure.clf(keep_observers=True) for i, a in self.dataPlotsSubplots.items(): a.cla() for i, a in self.dataPlotsSubplots.items(): if i == self.nAdcCh - 1: a.set_xlabel(u't [us]') a.set_ylabel('[V]') continue artist.setp(a.get_xticklabels(), visible=False) a.set_ylabel("#{:d}".format(i), rotation=0) nSamples = len(self.cd.adcData[0]) x = [self.cd.adcDt * i for i in range(nSamples)] for i, a in self.dataPlotsSubplots.items(): a.locator_params(axis='y', tight=True, nbins=4) a.yaxis.set_major_formatter(FormatStrFormatter('%7.4f')) a.set_xlim([0.0, self.cd.adcDt * nSamples]) a.step(x, array.array('f', self.cd.adcData[i]), where='post') if self.dataInfoText: if self.dataInfo is None: self.dataInfo = self.dataPlotsFigure.text( 0.02, 0.01, self.dataInfoText, ha='left', va='bottom', color='m', transform=self.dataPlotsFigure.transFigure) else: self.dataInfo.set_text(self.dataInfoText) self.dataPlotsCanvas.show() self.dataPlotsToolbar.update() return
def colorcycle(index=None, handles=None): '''Return a list of colors used for new lines in the axis. index -- optional integer index for a color from the cycle Return complete colorcycle when None. Return a single color when integer. Return a list of colors when iterable. handles -- optional matplotlib object or iterable of objects, whose color would be set according to the index. Return string or a list of strings. ''' from matplotlib import rcParams ccycle = rcParams['axes.color_cycle'][:] if index is None: rv = ccycle elif _isiterablenotstring(index): rv = [colorcycle(i) for i in index] else: nmidx = index % len(ccycle) rv = ccycle[nmidx] if handles is not None: from matplotlib.artist import setp if type(rv) is list: for c, h in zip(rv, handles): setp(h, color=c) else: setp(handles, color=rv) _redraw() return rv
def blanklinemarkers(lineid, filled=False, marker=None, color=None, width=None, **kw): '''Clear markerfacecolor for the specified lines and adjust the edge width and color according to the owner line. lineid -- integer zero based index or a matplotlib Line2D instance. Can be also a list of indices or Line2D objects. filled -- when True, restore the markerfacecolor color -- use instead of line color when specified width -- use for markeredge width if specified, otherwise use the line width. kw -- optional keyword arguments for additional line properties No return value. ''' from matplotlib.artist import setp linehandles = findlines(lineid) for hi in linehandles: mi = hi.get_marker() if marker is None else marker ci = hi.get_color() if color is None else color mfc = ci if filled else 'none' mec = ci mwi = hi.get_linewidth() if width is None else width hi.set_marker(mi) hi.set_markerfacecolor(mfc) hi.set_markeredgecolor(mec) hi.set_markeredgewidth(mwi) if kw: setp(hi, **kw) if linehandles: _redraw() return
def plot_flux_vs_time(self, ax=None): rpc = percentile(self.flux_raw, [0.5, 99.5, 50]) dpc = percentile(self.flux_detrended, [0.5, 99.5, 50]) d = 1.15 bbox_raw = rpc[-1] + d * (rpc[0] - rpc[-1]), rpc[-1] + d * (rpc[1] - rpc[-1]) bbox_dtr = dpc[-1] + d * (dpc[0] - dpc[-1]), dpc[-1] + d * (dpc[1] - dpc[-1]) offset = d * (rpc[1] - rpc[-1]) - d * (dpc[0] - dpc[-1]) ax.plot(self.time_detrended - self.bjdrefi, self.flux_detrended + 1.2*offset, label='detrended') ax.plot(self.time_raw - self.bjdrefi, self.flux_raw, label='raw') if self.zero_epoch: transits = self.zero_epoch + unique(epoch(self.time, self.zero_epoch, self.period)) * self.period [ax.axvline(t - self.bjdrefi, ls='--', alpha=0.5, lw=1) for t in transits if self.time[0] < t < self.time[-1]] def time2epoch(x): return (x + self.bjdrefi - self.zero_epoch) / self.period def epoch2time(x): return self.zero_epoch - self.bjdrefi + x * self.period secax = ax.secondary_xaxis('top', functions=(time2epoch, epoch2time)) secax.set_xlabel('Epoch') secax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.legend(loc='upper right') ax.autoscale(axis='x', tight=True) yp_offset = diff(ax.transData.inverted().transform([[0, 0], [0, 40]])[:, 1]) setp(ax, xlabel=f'Time - {self.bjdrefi} [BJD]', ylabel='Normalized flux', ylim=(bbox_raw[0] - yp_offset, bbox_dtr[1] + offset + yp_offset))
def restore_circle_props(self): mplartist.setp(self._circle, **self.default_props) for edge in (self.in_edges | self.out_edges) & self._graph.visible_edges: artist = self._graph.get_edge(edge) artist.update()
def __init__(self, edgecolor=None, facecolor=None, linewidth=None, antialiased=None, hatch=None, fill=1, **kwargs): """ The following kwarg properties are supported %(Patch)s """ artist.Artist.__init__(self) if edgecolor is None: edgecolor = mpl.rcParams['patch.edgecolor'] if facecolor is None: facecolor = mpl.rcParams['patch.facecolor'] if linewidth is None: linewidth = mpl.rcParams['patch.linewidth'] if antialiased is None: antialiased = mpl.rcParams['patch.antialiased'] self._edgecolor = edgecolor self._facecolor = facecolor self._linewidth = linewidth self._antialiased = antialiased self._hatch = hatch self.fill = fill if len(kwargs): artist.setp(self, **kwargs)
def grid(self, b=None, which='major', axis="both", **kwargs): """ Toggle the gridlines, and optionally set the properties of the lines. """ # their are some discrepancy between the behavior of grid in # axes_grid and the original mpl's grid, because axes_grid # explicitly set the visibility of the gridlines. super(Axes, self).grid(b, which=which, axis=axis, **kwargs) if not self._axisline_on: return if b is None: if self.axes.xaxis._gridOnMinor or self.axes.xaxis._gridOnMajor or \ self.axes.yaxis._gridOnMinor or self.axes.yaxis._gridOnMajor: b=True else: b=False self.gridlines.set_which(which) self.gridlines.set_axis(axis) self.gridlines.set_visible(b) if len(kwargs): martist.setp(self.gridlines, **kwargs)
def sq(self, bottom_left, size, color='black'): x = bottom_left[0] y = bottom_left[1] lines = self.ax.plot((x, x + size, x + size, x, x), (y, y, y + size, y + size, y), color=color) setp(lines, linewidth=5)
def _set_ticks_labels(ax, data, labels, positions, plot_opts): """Set ticks and labels on horizontal axis.""" # Set xticks and limits. ax.set_xlim([np.min(positions) - 0.5, np.max(positions) + 0.5]) ax.set_xticks(positions) label_fontsize = plot_opts.get('label_fontsize') label_rotation = plot_opts.get('label_rotation') if label_fontsize or label_rotation: from matplotlib.artist import setp if labels is not None: if not len(labels) == len(data): msg = "Length of `labels` should equal length of `data`." raise(ValueError, msg) xticknames = ax.set_xticklabels(labels) if label_fontsize: setp(xticknames, fontsize=label_fontsize) if label_rotation: setp(xticknames, rotation=label_rotation) return
def grid(self, b=None, which='major', axis="both", **kwargs): """ Toggle the gridlines, and optionally set the properties of the lines. """ # their are some discrepancy between the behavior of grid in # axes_grid and the original mpl's grid, because axes_grid # explicitly set the visibility of the gridlines. super().grid(b, which=which, axis=axis, **kwargs) if not self._axisline_on: return if b is None: if self.axes.xaxis._gridOnMinor or self.axes.xaxis._gridOnMajor or \ self.axes.yaxis._gridOnMinor or self.axes.yaxis._gridOnMajor: b = True else: b = False self.gridlines.set_which(which) self.gridlines.set_axis(axis) self.gridlines.set_visible(b) if len(kwargs): martist.setp(self.gridlines, **kwargs)
def map_pick(self, event): """ handles the pick event on the station map :param event: :return: """ # print event.mouseevent.key, event.mouseevent.button if event.artist in self.artists: if not event.mouseevent.key or event.mouseevent.key != 'control': self.selected_stations.clear() stations = self.artists[event.artist] if len(event.ind) != 0: for subplotnum, dataind in enumerate(event.ind): self.selected_stations.add(stations[dataind]) # update tree view accordingly # self._ignore_selection_change = True # self._ignore_selection_change = False # emit selection changed signal # self.ui.treeWidget_stations.emit(QtCore.SIGNAL("selectionChanged()")) if self.useblit: for station, annotation_artist in self._annotation_artists.iteritems(): artist.setp(annotation_artist, color='red' if station in self.selected_stations else 'black') self._axes.draw_artist(annotation_artist) self.blit(self._axes.bbox) else: self.update_figure() # tell others that the map selection is changed self.selection_changed.emit() else: pass return True
def __init__(self, edgecolor=None, facecolor=None, linewidth=None, antialiased = None, hatch = None, fill=True, **kwargs ): """ The following kwarg properties are supported %(Patch)s """ artist.Artist.__init__(self) if linewidth is None: linewidth = mpl.rcParams['patch.linewidth'] if antialiased is None: antialiased = mpl.rcParams['patch.antialiased'] self.set_edgecolor(edgecolor) self.set_facecolor(facecolor) self.set_linewidth(linewidth) self.set_antialiased(antialiased) self.set_hatch(hatch) self.fill = fill self._combined_transform = transforms.IdentityTransform() if len(kwargs): artist.setp(self, **kwargs)
def popup_for_plot(self, event_for_close_popup, handle_ticks_configuration): self.plot_popup = tk.Toplevel() self.plot_popup.grab_set() self.plot_popup.wm_title("Plot") self.plot_popup.protocol("WM_DELETE_WINDOW", event_for_close_popup) figure = Figure(dpi=100) self.plot = figure.add_subplot(111) mat_art.setp(self.plot, **PropertiesDictionaries.axes_properties_dict) self.plot.grid(**PropertiesDictionaries.grid_properties_dict) self.plot.tick_params( **dict( list( PropertiesDictionaries.ticks_properties_dict.items())[:2]), **dict( list(PropertiesDictionaries.ticks_properties_dict.items()) [3:7]), **dict( list( PropertiesDictionaries.ticks_properties_dict.items())[8:])) handle_ticks_configuration() canvas = FigureCanvasTkAgg(figure, self.plot_popup) canvas.get_tk_widget().pack(side="top", fill="both", expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self.plot_popup) toolbar.update() canvas._tkcanvas.pack() canvas.show()
def _plot(fig, hists, labels, N, show_ticks=False): """ Plot pair-wise correlation histograms """ if N<=1: fig.text(0.5,0.5,"No correlation plots when only one variable",ha="center",va="center") return vmin, vmax = inf, -inf for data,_,_ in hists.values(): positive = data[data>0] if len(positive) > 0: vmin = min(vmin,numpy.amin(positive)) vmax = max(vmax,numpy.amax(positive)) norm = colors.LogNorm(vmin=vmin, vmax=vmax, clip=False) #norm = colors.Normalize(vmin=vmin, vmax=vmax) mapper = image.FigureImage(fig) mapper.set_array(numpy.zeros(0)) mapper.set_cmap(cmap=COLORMAP) mapper.set_norm(norm) ax = {} Nr = Nc = N-1 for i in range(0,N-1): for j in range(i+1,N): sharex = ax.get((0,j), None) sharey = ax.get((i,i+1), None) a = fig.add_subplot(Nr,Nc,(Nr-i-1)*Nc + j, sharex=sharex, sharey=sharey) ax[(i,j)] = a a.xaxis.set_major_locator(MaxNLocator(4,steps=[1,2,4,5,10])) a.yaxis.set_major_locator(MaxNLocator(4,steps=[1,2,4,5,10])) data,x,y = hists[(i,j)] data = numpy.clip(data,vmin,vmax) a.pcolorfast(y,x,data,cmap=COLORMAP,norm=norm) # Show labels or hide ticks if i != 0: artist.setp(a.get_xticklabels(),visible=False) if i == N-2 and j == N-1: a.set_xlabel(labels[j]) #a.xaxis.set_label_position("top") #a.xaxis.set_offset_position("top") if not show_ticks: a.xaxis.set_ticks([]) if j == i+1: a.set_ylabel(labels[i]) else: artist.setp(a.get_yticklabels(),visible=False) if not show_ticks: a.yaxis.set_ticks([]) a.zoomable=True # Adjust subplots and add the colorbar fig.subplots_adjust(left=.07, bottom=.07, top=.9, right=0.85, wspace=0.0, hspace=0.0) cax = fig.add_axes([0.88, 0.2, 0.04, 0.6]) fig.colorbar(mapper, cax=cax, orientation='vertical') return ax
def __init__(self, master, cd, dataFigSize=(13, 12.5)): self.master = master self.cd = cd self.nAdcCh = self.cd.nAdcCh self.nSdmCh = self.cd.nCh self.adcSdmCycRatio = self.cd.adcSdmCycRatio self.master.wm_title("Topmetal-S 1mm version x19 array data") # appropriate quitting self.master.wm_protocol("WM_DELETE_WINDOW", self.quit) # button = tk.Button(master=self.master, text='Re-sample', command=self.get_and_plot_data) button.pack(side=tk.BOTTOM, fill=tk.X) # frame for plotting self.dataPlotsFrame = tk.Frame(self.master) self.dataPlotsFrame.pack(side=tk.TOP, fill=tk.BOTH, expand=True) self.dataPlotsFrame.bind("<Configure>", self.on_resize) self.dataPlotsFigure = Figure(figsize=dataFigSize, dpi=72) self.dataPlotsFigure.subplots_adjust(left=0.1, right=0.98, top=0.98, bottom=0.05, hspace=0, wspace=0) # x-axis is shared dataPlotsSubplotN = self.dataPlotsFigure.add_subplot(self.nAdcCh, 1, self.nAdcCh, xlabel='t [us]', ylabel='[V]') self.dataPlotsSubplots = [ self.dataPlotsFigure.add_subplot(self.nAdcCh, 1, i + 1, sharex=dataPlotsSubplotN) for i in xrange(self.nAdcCh - 1) ] for a in self.dataPlotsSubplots: artist.setp(a.get_xticklabels(), visible=False) self.dataPlotsSubplots.append(dataPlotsSubplotN) self.dataPlotsCanvas = FigureCanvasTkAgg(self.dataPlotsFigure, master=self.dataPlotsFrame) self.dataPlotsCanvas.show() self.dataPlotsCanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) self.dataPlotsToolbar = NavigationToolbar2TkAgg( self.dataPlotsCanvas, self.dataPlotsFrame) self.dataPlotsToolbar.update() self.dataPlotsCanvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) self.dataPlotsCanvas.mpl_connect('key_press_event', self.on_key_event) # self.plot_data()
def grid(self, b=None, **kwargs): if not self._axisline_on: super(Axes, self).grid(b, **kwargs) return if b is None: b = not self.gridlines.get_visible() self.gridlines.set_visible(b) if len(kwargs): martist.setp(self.gridlines, **kwargs)
def cla(self): self._get_base_axes_attr("cla")(self) martist.setp(self.get_children(), visible=False) self._get_lines = self._parent_axes._get_lines if self._axisbelow: self.xaxis.set_zorder(0.5) self.yaxis.set_zorder(0.5) else: self.xaxis.set_zorder(2.5) self.yaxis.set_zorder(2.5)
def _show_legend(ax): """Utility function to show legend.""" leg = ax.legend(loc=1, shadow=True, fancybox=True, labelspacing=0.2, borderpad=0.15) ltext = leg.get_texts() llines = leg.get_lines() from matplotlib.artist import setp setp(ltext, fontsize='small') setp(llines, linewidth=1)
def changeStyle(self, curveRef, style): """change curve style curveRef -- internal reference to curves style -- style dictionary """ stylestr, properties = self.__translateStyles(style) #FIXME: we discard stylestr because it seems there's no way # it can be changed afterwards. setp((curveRef,), **properties) self.subplot.legend(**legendBoxProperties())
def animate_function(i): global a if a < time_steps: line.set_data(X, Array[i, :]) setp(line, linewidth=2, color='k') # line = Line2D(X, Array[:,i], color='red', linewidth=2) else: line.set_data(X, Array[-1, :]) a += 1 return line
def animate_function(i): global a if a<time_steps: lines[1].set_data(X, Array[i,:]) setp(lines[1], linewidth=2, color='r') else: lines[1].set_data(X, Array[-1,:]) a+=1 return lines
def animate_function(i): global a if a<time_steps: line.set_data(X, Array[i,:]) setp(line, linewidth=2, color='r') # line = Line2D(X, Array[:,i], color='red', linewidth=2) else: line.set_data(X, Array[-1,:]) a+=1 return line
def changeStyle(self, curveRef, style): """change curve style curveRef -- internal reference to curves style -- style dictionary """ stylestr, properties = self.__translateStyles(style) #FIXME: we discard stylestr because it seems there's no way # it can be changed afterwards. setp((curveRef, ), **properties) self.subplot.legend(**legendBoxProperties())
def animate_function(i): global a if a < time_steps: lines[1].set_data(X, Array[i, :]) setp(lines[1], linewidth=2, color='r') else: lines[1].set_data(X, Array[-1, :]) a += 1 return lines
def test_setp(): # Check arbitrary iterables fig, axes = plt.subplots() lines1 = axes.plot(range(3)) lines2 = axes.plot(range(3)) martist.setp(chain(lines1, lines2), 'lw', 5) plt.setp(axes.spines.values(), color='green') # Check `file` argument sio = io.StringIO() plt.setp(lines1, 'zorder', file=sio) assert sio.getvalue() == ' zorder: any number \n'
def __init__(self): self.fig = Figure() self.ax1 = self.fig.add_subplot(311) self.ax2 = self.fig.add_subplot(312, sharex = self.ax1, sharey = self.ax1) self.ax3 = self.fig.add_subplot(313, sharex = self.ax1, sharey = self.ax1) self.ax1.set_ylim(-0.2,1.5) self.fig.subplots_adjust(hspace=0) art.setp(self.ax1.get_xticklabels(), visible=False) art.setp(self.ax2.get_xticklabels(), visible=False) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self)
def animate_function(i): global a if i == 0: time.sleep(.3) if a < time_steps: lines[1].set_data(X, Array[i, :]) setp(lines[1], linewidth=2.6, color='k') else: lines[1].set_data(X, Array[-1, :]) a += 1 return lines
def animate_function(i): global a if i == 0: time.sleep(0.3) if a < time_steps: lines[1].set_data(X, Array[i, :]) setp(lines[1], linewidth=2.6, color="k") else: lines[1].set_data(X, Array[-1, :]) a += 1 return lines
def show(self, hardrefresh=True): """ Show graphics dependent on the current buffering state. """ if not hardrefresh: return if not self.buffering: if self.loc is not None: for sp in self.subplots: lines = [] labels = [] i = 0 for line in sp['lines']: i += 1 if line is not None: lines.append(line[0]) lbl = line[0].get_label() if lbl == '': lbl = str(i) labels.append(lbl) if len(lines): fp = FP(size=rcParams['legend.fontsize']) #fsz = fp.get_size_in_points() - len(lines) fsz = fp.get_size_in_points() - max(len(lines),self.cols) #fp.set_size(max(fsz,6)) fp.set_size(max(fsz,8)) sp['axes'].legend(tuple(lines), tuple(labels), self.loc, prop=fp) #else: # sp['axes'].legend((' ')) from matplotlib.artist import setp fpx = FP(size=rcParams['xtick.labelsize']) xts = fpx.get_size_in_points()- (self.cols)/2 fpy = FP(size=rcParams['ytick.labelsize']) yts = fpy.get_size_in_points() - (self.rows)/2 fpa = FP(size=rcParams['axes.labelsize']) fpat = FP(size=rcParams['axes.titlesize']) axsize = fpa.get_size_in_points() tsize = fpat.get_size_in_points()-(self.cols)/2 for sp in self.subplots: ax = sp['axes'] ax.title.set_size(tsize) setp(ax.get_xticklabels(), fontsize=xts) setp(ax.get_yticklabels(), fontsize=yts) off = 0 if self.cols > 1: off = self.cols ax.xaxis.label.set_size(axsize-off) off = 0 if self.rows > 1: off = self.rows ax.yaxis.label.set_size(axsize-off)
def cla(self): super().cla() martist.setp(self.get_children(), visible=False) self._get_lines = self._parent_axes._get_lines # In mpl's Axes, zorders of x- and y-axis are originally set # within Axes.draw(). if self._axisbelow: self.xaxis.set_zorder(0.5) self.yaxis.set_zorder(0.5) else: self.xaxis.set_zorder(2.5) self.yaxis.set_zorder(2.5)
def OnMousePress(event): global canvas, MousePress, SelectedTrack, axis, MousePressTime if time() - MousePressTime < 0.2: return for a in axis.artists: if a.label != "Poly": contains, attrd = a.contains(event) if contains: tup = a.xy x0, y0 = tup[0], tup[1] MousePress = x0, y0, event.xdata, event.ydata # Check if we selected the zoom controls (copied from ImageView.py) if a.label == "zoom_container" or a.label == "zoom_box": setp(z_box, alpha=1) setp(z_box, edgecolor="w") SelectedTrack = -100 # We'll use the code -100 to identify whether the zoom controls are selected (to avoid declaring more global variables) break SelectedTrack = int("".join(next(filter(str.isdigit, a.label)))) setp(a, linewidth=4) else: setp(a, linewidth=1) canvas.draw_idle() MousePressTime = time()
def cla(self): self._get_base_axes_attr("cla")(self) martist.setp(self.get_children(), visible=False) self._get_lines = self._parent_axes._get_lines # In mpl's Axes, zorders of x- and y-axis are originally set # within Axes.draw(). if self._axisbelow: self.xaxis.set_zorder(0.5) self.yaxis.set_zorder(0.5) else: self.xaxis.set_zorder(2.5) self.yaxis.set_zorder(2.5)
def tickrot(axes, figure, rotype='horizontal', x=True, y=True): """ Matplot rotation of ticks labels :param axes: :param figure: :param rotype: :param x: :param y: :return: """ if y: setp(axes.get_yticklabels(), rotation=rotype) if x: setp(axes.get_xticklabels(), rotation=rotype) figure.canvas.draw()
def plot_histogram(git_log, filtered_log, match_description, argv): title = os.path.basename(os.getcwd()) + ' Count of ' + match_description all_dates = [ mdates.date2num(entry['committer.date'].astimezone( datetime.timezone.utc)) for entry in git_log ] filtered_dates = [ mdates.date2num(entry['committer.date'].astimezone( datetime.timezone.utc)) for entry in filtered_log ] pyplot.style.use('bmh') fig, ax1 = pyplot.subplots(num=title, figsize=(8.8, 4), constrained_layout=True) ax2 = ax1.twinx() ax1.set(title=title) ax1.set_ylabel('Matching commit count', color='C0') ax1.tick_params('y', colors='C0') ax1.grid(axis='y') ax2.set_ylabel('All commits count', color='C1') ax2.tick_params('y', colors='C1') ax2.grid(axis='y') all_dates_counts, bins = np.histogram(all_dates, bins=36) filtered_dates_counts, _ = np.histogram(filtered_dates, bins=bins) ax1.hist(bins[:-1], bins, weights=filtered_dates_counts, histtype='stepfilled', color='C0') ax2.hist(bins[:-1], bins, weights=all_dates_counts, histtype='step', color='C1') locator = mdates.AutoDateLocator() ax1.xaxis.set_major_locator(locator) ax1.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator)) artist.setp(ax1.get_xticklabels(), rotation=30, ha='right') for spine in ['top', 'right']: ax1.spines[spine].set_visible(False) ax2.spines[spine].set_visible(False)
def Profile_Matrix(frame): #Much of this is stolen from https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py range_padding = 0.05 df = frame._get_numeric_data() n = df.columns.size fig, axes = plots._subplots(naxes=n * n, squeeze=False) # no gaps between subplots fig.subplots_adjust(wspace=0, hspace=0) mask = com.notnull(df) boundaries_list = [] for a in df.columns: values = df[a].values[mask[a].values] rmin_, rmax_ = np.min(values), np.max(values) rdelta_ext = (rmax_ - rmin_) * range_padding / 2. boundaries_list.append((rmin_ - rdelta_ext, rmax_ + rdelta_ext)) for i, a in zip(lrange(n), df.columns): for j, b in zip(lrange(n), df.columns): common = (mask[a] & mask[b]).values nbins = 100 (xmin, xmax) = boundaries_list[i] ax = axes[i, j] Profile(df[a][common], df[b][common], nbins, xmin, xmax, ax) ax.set_xlabel('') ax.set_ylabel('') #plots._label_axis(ax, kind='x', label=b, position='bottom', rotate=True) #plots._label_axis(ax, kind='y', label=a, position='left') if j != 0: ax.yaxis.set_visible(False) if i != n - 1: ax.xaxis.set_visible(False) for ax in axes.flat: setp(ax.get_xticklabels(), fontsize=8) setp(ax.get_yticklabels(), fontsize=8) return axes
def test_setp(): # Check empty list plt.setp([]) plt.setp([[]]) # Check arbitrary iterables fig, ax = plt.subplots() lines1 = ax.plot(range(3)) lines2 = ax.plot(range(3)) martist.setp(chain(lines1, lines2), 'lw', 5) plt.setp(ax.spines.values(), color='green') # Check *file* argument sio = io.StringIO() plt.setp(lines1, 'zorder', file=sio) assert sio.getvalue() == ' zorder: float\n'
def grid(self, b=None, **kwargs): """ Toggel the gridlines, and optionally set the properties of the lines. """ super(Axes, self).grid(b, **kwargs) if not self._axisline_on: return if b is None: if self.axes.xaxis._gridOnMinor or self.axes.xaxis._gridOnMajor or \ self.axes.yaxis._gridOnMinor or self.axes.yaxis._gridOnMajor: b=True else: b=False self.gridlines.set_visible(b) if len(kwargs): martist.setp(self.gridlines, **kwargs)
def plot(self, windir, windspeed, windfrequency): self.windir = [] self.windspeed = [] for i, frequency in enumerate(windfrequency): for n in range(frequency): self.windir.append(windir[i]) self.windspeed.append(windspeed[i]) self.axes.clear() self.axes.bar(self.windir, self.windspeed, normed=True, opening=0.8, edgecolor='white') l = self.axes.legend(borderaxespad=-3.8) setp(l.get_texts(), fontsize=8) # force redraw the canvas self.fig.canvas.draw()
def _label_axis(ax, kind='x', label='', position='top', ticks=True, rotate=False): from matplotlib.artist import setp if kind == 'x': ax.set_xlabel(label, visible=True) ax.xaxis.set_visible(True) ax.xaxis.set_ticks_position(position) ax.xaxis.set_label_position(position) if rotate: setp(ax.get_xticklabels(), rotation=90) elif kind == 'y': ax.yaxis.set_visible(True) ax.set_ylabel(label, visible=True) #ax.set_ylabel(a) ax.yaxis.set_ticks_position(position) ax.yaxis.set_label_position(position) return
def plot_stat_fig(data_1,data_2,data_3,data_4,data_5,kind = 'boxplot'): fig = plt.subplots(figsize = (16,12)) gs = gridspec.GridSpec(2,16) fontsize = 30 label_fontsize = 25 ticklabel_fontsize = 15 def get_plot(data, title = None, kind = 'barplot'): if kind == 'barplot': sns.barplot(data = data, ax=ax) elif kind == 'boxplot': sns.boxplot(data = data, ax=ax) elif kind == 'violinplot': sns.violinplot(data = data, ax=ax) elif kind == 'stripplot': sns.stripplot(data = data, ax=ax, jitter=True) ax.set_title(title, fontsize = fontsize) for i in range(5): i = i + 1 if i == 1 : ax = plt.subplot(gs[0,:]) # sns.barplot(data = distance_data_1, ax=ax) get_plot(data_1, title = 'd_1', kind = kind) elif i == 2: ax = plt.subplot(gs[1,:6]) get_plot(data_2, title = 'd_2', kind = kind) ax.set_ylabel('Mean', fontsize = label_fontsize) elif i == 3: ax = plt.subplot(gs[1,6:12]) get_plot(data_3, title = 'd_3', kind = kind) ax.set_title('d_3', fontsize = fontsize) elif i == 4: ax = plt.subplot(gs[1,12:14]) get_plot(data_4, title = 'd_4', kind = kind) elif i == 5: ax = plt.subplot(gs[1,14:]) get_plot(data_5, title = 'd_5', kind = kind) setp(ax.get_yticklabels(), fontsize = ticklabel_fontsize) ax.set_xticks(ax.get_xticks() - [0.5]) setp(ax.get_xticklabels(), fontsize = ticklabel_fontsize, rotation = 45) ax.tick_params(width = 0,length = 0) plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace = 6, hspace = 0.6) plt.show()
def render(self, axes, x, y): color = axes._get_lines.color_cycle axes.scatter(x, y, color=color.next(), s=3) axes.set_aspect('equal') divider = make_axes_locatable(axes) axesTop = divider.append_axes('top', 1.2, pad=0.1, sharex=axes) axesRight = divider.append_axes('right', 1.2, pad=0.2, sharey=axes) # Make labels invisible: setp(axesTop.get_xticklabels() + axesRight.get_yticklabels(), visible=False) axesTop.hist(x, bins=20, fc='k', ec=None, normed=True) axesRight.hist(y, bins=20, fc='k', ec=None, orientation='horizontal', normed=True) [t.set_rotation(-90) for t in axesRight.get_xticklabels()]
def update_legend(self): Util.debug(1, "ScatterPlot.update_legend", "") if self.get('legend').get('loc') == 'none' or self.plot() == None or self.plot().axes() == None: return # We need to apply the font dict to the Text instances themselves, since # Legend only accepts a FontProperties object legendOptions = self.getMpl('legend') font = legendOptions['font'] titleFont = legendOptions['titleFont'] del legendOptions['font'] del legendOptions['titleFont'] self.plot().axes().legend(**legendOptions) setp(self.plot().axes().get_legend().get_texts(), **font) setp(self.plot().axes().get_legend().get_title(), **titleFont) self.plot().redraw()
def main(): if len(sys.argv) == 1: f = 'data/he10_2013_1225_214621.dat' else: f = sys.argv[1] d1 = plot_temps.format_he10_data(f) d2 = plot_temps.format_he10_data(f) # plot fig = plt.figure() ax1 = plt.subplot2grid((1, 2), (0, 0)) ax2 = plt.subplot2grid((1, 2), (0, 1)) plot_temps.plot_he10_data(ax1, *d1) plot_temps.plot_he10_data(ax2, *d2) # range x1min = dt.datetime(2014, 1, 1) x1max = dt.datetime(2014, 1, 8) x2min = dt.datetime(2014, 1, 11) x2max = dt.datetime(2014, 1, 18) ax1.set_xlim(x1min, x1max) ax2.set_xlim(x2min, x2max) # tune ax1.grid() ax1.grid(which='minor') ax2.grid() ax2.grid(which='minor') ax1.semilogy() ax2.semilogy() plt.subplots_adjust(wspace=0.05) ax1.set_ylabel('Temperature [K]', fontsize=15) ma.setp(ax2.get_yticklabels(), visible=False) daysLoc1 = md.DayLocator(interval=2) daysLoc2 = md.DayLocator(interval=2) ax1.xaxis.set_major_locator(daysLoc1) ax2.xaxis.set_major_locator(daysLoc2) plt.legend(ncol=3, bbox_to_anchor=[0.92, 1.0]) xfmt = md.DateFormatter('%b.%d') ax1.xaxis.set_major_formatter(xfmt) ax2.xaxis.set_major_formatter(xfmt) ax1.set_title('Rotation with 20 rpm', fontsize=15) ax2.set_title('No rotaion', fontsize=15) plt.savefig("eps/comp_temps.eps") plt.show()
def formatting(self): ax1, ax2 = self.ax1, self.ax2 ax1.grid(True, color=self.theme['grid'], alpha=0.5) ax2.grid(True, color=self.theme['grid'], alpha=0.5) for region in ['bottom', 'top', 'left', 'right']: ax1.spines[region].set_color(self.theme['spines']) ax2.spines[region].set_color(self.theme['spines']) ax1.tick_params(axis='x', colors=self.theme['ticks']) ax2.tick_params(axis='x', colors=self.theme['ticks']) ax1.tick_params(axis='y', colors=self.theme['ticks']) ax2.tick_params(axis='y', colors=self.theme['ticks']) ax1.xaxis.label.set_color(self.theme['labels']) ax2.xaxis.label.set_color(self.theme['labels']) ax1.yaxis.label.set_color(self.theme['labels']) ax2.yaxis.label.set_color(self.theme['labels']) ax1.set_ylabel('USD/BTC') # hide x labels of upper subplot setp(ax1.get_xticklabels(), visible=False)
def box_plot(self): data = dict() for key, value in self.args.data.items(): if value['type_0_tx'] < MIN_PKT_COUNT: continue k = self.get_key(key[0], key[1], key[2]) if k is None: continue k = '%.2f' % (k) if k not in data: data[k] = [] v = self.get_value(value) if v is not None: data[k].append(v) data = self.post_process(data) ax = self.add_subplot(111) X = sorted(data.keys(), key=lambda t: float(t)) Y = [data[x] for x in X] lines = ax.boxplot(Y, sym='', whis=[10, 90], widths=0.4, patch_artist=True) setp(lines['medians'], color='k', linewidth=1) setp(lines['boxes'], color='grey', linewidth=0.5) setp(lines['whiskers'], linewidth=0.5, color='grey', linestyle='solid') setp(lines['caps'], linewidth=0.5, color='grey') xmax = max([float(x) for x in X]) if xmax > 1: step = 0.5 else: step = 0.1 xticks = [X.index('%.2f' % (x))+1 for x in np.arange(0, xmax+0.01, step)] ax.set_xticks(xticks) ax.set_xticklabels(['%.1f' % (x) for x in np.arange(0, xmax+0.01, step)]) ax.set_xlabel(self.xlabel) ax.set_ylabel(self.ylabel) return ax
def plot_corr(dcorr, xnames=None, ynames=None, title=None, normcolor=False, ax=None): """Plot correlation of many variables in a tight color grid. This creates a new figure Parameters ---------- dcorr : ndarray correlation matrix xnames : None or list of strings labels for x axis. If None, then the matplotlib defaults are used. If it is an empty list, [], then not ticks and labels are added. ynames : None or list of strings labels for y axis. If None, then the matplotlib defaults are used. If it is an empty list, [], then not ticks and labels are added. title : None or string title for figure. If None, then default is added. If title='', then no title is added normcolor : bool If false (default), then the color coding range corresponds to the lowest and highest correlation (automatic choice by matplotlib). If true, then the color range is normalized to (-1, 1). If this is a tuple of two numbers, then they define the range for the color bar. ax : Matplotlib AxesSubplot instance, optional If `ax` is None, then a figure is created. If an axis instance is given, then only the main plot but not the colorbar is created. Returns ------- fig : Matplotlib figure instance If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. """ if ax is None: create_colorbar = True else: create_colorbar = False fig, ax = utils.create_mpl_ax(ax) from matplotlib import cm from matplotlib.artist import setp nvars = dcorr.shape[0] if (ynames is None) and (not xnames is None): ynames = xnames if title is None: title = 'Correlation Matrix' if isinstance(normcolor, tuple): vmin, vmax = normcolor elif normcolor: vmin, vmax = -1.0, 1.0 else: vmin, vmax = None, None axim = ax.imshow(dcorr, cmap=cm.jet, interpolation='nearest', extent=(0,30,0,30), vmin=vmin, vmax=vmax) if ynames: ax.set_yticks(np.arange(nvars)+0.5) ax.set_yticklabels(ynames[::-1], minor=True, fontsize='small', horizontalalignment='right') elif ynames == []: ax.set_yticks([]) if xnames: ax.set_xticks(np.arange(nvars)+0.5) ax.set_xticklabels(xnames, minor=True, fontsize='small', rotation=45, horizontalalignment='right') #some keywords don't work in previous line ? #TODO: check if this is redundant setp(ax.get_xticklabels(), fontsize='small', rotation=45, horizontalalignment='right') elif xnames == []: ax.set_xticks([]) if not title == '': ax.set_title(title) if create_colorbar: fig.colorbar(axim) return fig
def _label_axes(ax, x_label, y_label, fontsize=20, rotate_x_ticks=True): ax.set_xlabel(x_label, fontsize=fontsize) ax.set_ylabel(y_label, fontsize=fontsize) if rotate_x_ticks: from matplotlib.artist import setp setp(ax.get_xticklabels(), rotation=90)
def cla(self): super(ParasiteAxes, self).cla() martist.setp(self.get_children(), visible=False) self._get_lines = self._parent_axes._get_lines
def myscatter_matrix(frame, pred_values=[], mypred_values=[], clf=None, alpha=0.5, figsize=None, ax=None, grid=False, diagonal='hist', marker='.', density_kwds={}, hist_kwds={}, **kwds): # enhanced pd.tools.plotting.scatter_matrix import pandas as pd import pandas.core.common as com import numpy as np from matplotlib.colors import ListedColormap #print "in myscatter_matrix..." #print " clf=%s" % clf #if len(mypred_values) == 0: # print "mypred_values is empty" #else: # print "mypred_values:{0}".format(mypred_values) from matplotlib.artist import setp df = frame._get_numeric_data() n = df.columns.size fig, axes = pd.tools.plotting._subplots(nrows=n, ncols=n, figsize=figsize, ax=ax, squeeze=False) # no gaps between subplots fig.subplots_adjust(wspace=0, hspace=0) mask = com.notnull(df) marker = pd.tools.plotting._get_marker_compat(marker) for i, a in zip(range(n), df.columns): for j, b in zip(range(n), df.columns): ax = axes[i, j] if i == j: values = df[a].values[mask[a].values] # Deal with the diagonal by drawing a histogram there. if diagonal == 'hist': ax.hist(values, **hist_kwds) elif diagonal in ('kde', 'density'): from scipy.stats import gaussian_kde y = values gkde = gaussian_kde(y) ind = np.linspace(y.min(), y.max(), 1000) ax.plot(ind, gkde.evaluate(ind), **density_kwds) else: common = (mask[a] & mask[b]).values # begin my mods #ax.scatter(df[b][common], df[a][common], # marker=marker, alpha=alpha, **kwds) if len(pred_values) == 0 and len(mypred_values) == 0: ax.scatter(df[b][common], df[a][common], marker=marker, alpha=alpha, **kwds) elif len(pred_values) > 0 and len(mypred_values) == 0: ax.scatter(df[b][common][pred_values == 1], df[a][common][pred_values == 1], marker='D', color='r', label="y == 1", alpha=alpha, **kwds) ax.scatter(df[b][common][pred_values == 0], df[a][common][pred_values == 0], marker='o', color='b', label="y == 0", alpha=alpha, **kwds) #print "myscatter_matrix: obs_n(y == 0)={0:,}".format(len(df[a][common][pred_values == 0])) #print "myscatter_matrix: obs_n(y == 1)={0:,}".format(len(df[a][common][pred_values == 1])) myhandles, mylabels = ax.get_legend_handles_labels() else: ## Create color maps cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF', '#AAFFAA']) cmap_bold = ListedColormap(['#FF0000', '#0000FF', '#00FF00']) xbb, xaa, Z = mybuild_colormesh(df, j, b, i, a, common, clf) ax.pcolormesh(xbb, xaa, Z, cmap=cmap_light) #label="true +ve", c='g', marker="d" #label="false -ve", c='r', marker="x" #label="false +ve", c='k', marker="*" #label="true -ve", c='b', marker="o" # not displayed ax.scatter( df[b][common][np.logical_and(pred_values == 1, mypred_values == 1)], df[a][common][np.logical_and(pred_values == 1, mypred_values == 1)], marker='d', color='g', label=" true +ve", cmap=cmap_bold, alpha=alpha, **kwds) ax.scatter( df[b][common][np.logical_and(pred_values == 1, mypred_values == 0)], df[a][common][np.logical_and(pred_values == 1, mypred_values == 0)], marker='x', color='r', label="false -ve", cmap=cmap_bold, alpha=alpha, **kwds) ax.scatter( df[b][common][np.logical_and(pred_values == 0, mypred_values == 1)], df[a][common][np.logical_and(pred_values == 0, mypred_values == 1)], marker='*', color='k', label="false +ve", cmap=cmap_bold, alpha=alpha, **kwds) #ax.grid(True) myhandles, mylabels = ax.get_legend_handles_labels() # end my mods ax.set_xlabel('') ax.set_ylabel('') pd.tools.plotting._label_axis(ax, kind='x', label=b, position='bottom', rotate=True) ax.set_xlabel(b, fontsize=4) pd.tools.plotting._label_axis(ax, kind='y', label=a, position='left') ax.set_ylabel(a, fontsize=4) if j!= 0: ax.yaxis.set_visible(False) if i != n-1: ax.xaxis.set_visible(False) for ax in axes.flat: setp(ax.get_xticklabels(), fontsize=2) # was 8 in original version setp(ax.get_yticklabels(), fontsize=4) # begin my mods if len(pred_values) > 0 or len(mypred_values) > 0: fig.legend(myhandles, mylabels, loc='best', shadow=True, fontsize='x-small') # end my mods return axes
def plot(self, profile, statsResults): if len(profile.profileDict) <= 0 or self.preferences['Selected group feature'] == '' or len(profile.samplesInGroup1) == 0 or len(profile.samplesInGroup2) == 0: 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()) # *** Get data for each group feature = self.preferences['Selected group feature'] if self.fieldToPlot == "Number of sequences": data1, data2 = profile.getFeatureCounts(feature) else: # Proportion of sequences (%) data1, data2 = profile.getFeatureProportions(feature) # *** Set figure size self.fig.clear() self.fig.set_size_inches(self.figWidth, self.figHeight) padding = 0.25 # inches xOffsetFigSpace = (0.4 + padding)/self.figWidth yOffsetFigSpace = (0.3 + padding)/self.figHeight axesBoxPlot = self.fig.add_axes([xOffsetFigSpace, yOffsetFigSpace, 1.0 - xOffsetFigSpace - (2*padding)/self.figWidth, 1.0 - yOffsetFigSpace - (2*padding)/self.figHeight]) # box plot data = [data1, data2] bp = axesBoxPlot.boxplot(data, notch=0, sym='k+', vert=1, whis=1.5) setp(bp['boxes'], color='black') setp(bp['whiskers'], color='black',linestyle='-') setp(bp['medians'], color='black') # fill boxes with desired colors colours = [group1Colour, group2Colour] for i in xrange(0, len(data)): # get box coordinates box = bp['boxes'][i] boxCoords = zip(box.get_xdata()[0:5],box.get_ydata()[0:5]) # colour in box boxPolygon = Polygon(boxCoords, facecolor=colours[i]) axesBoxPlot.add_patch(boxPolygon) # draw the median lines back over what we just filled in med = bp['medians'][i] axesBoxPlot.plot(med.get_xdata()[0:2], med.get_ydata()[0:2], 'k') # mark average if self.bShowAverages: for i in xrange(0,2): med = bp['medians'][i] axesBoxPlot.plot([np.average(med.get_xdata())], [np.average(data[i])], color='w', marker='*', markeredgecolor='k') # *** P-value label if self.bShowPvalue and statsResults.profile != None: pValueStr = statsResults.getFeatureStatisticAsStr(feature, 'pValuesCorrected') axesBoxPlot.text(1.0, 1.0, r'$p$ = ' + pValueStr, horizontalalignment='right', verticalalignment='bottom', transform=axesBoxPlot.transAxes) # *** Prettify scatter plot if self.preferences['Truncate feature names']: length = self.preferences['Length of truncated feature names'] if len(feature) > length+3: feature = feature[0:length] + '...' axesBoxPlot.set_title(feature) axesBoxPlot.set_ylabel(self.fieldToPlot) axesBoxPlot.set_xticklabels([profile.groupName1, profile.groupName2]) for a in axesBoxPlot.yaxis.majorTicks: a.tick1On=True a.tick2On=False for a in axesBoxPlot.xaxis.majorTicks: a.tick1On=True a.tick2On=False for line in axesBoxPlot.yaxis.get_ticklines(): line.set_color(axesColour) for line in axesBoxPlot.xaxis.get_ticklines(): line.set_color(axesColour) for loc, spine in axesBoxPlot.spines.iteritems(): if loc in ['right','top']: spine.set_color('none') else: spine.set_color(axesColour) #axesBoxPlot.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) #axesBoxPlot.set_axisbelow(True) self.updateGeometry() self.draw()