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 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 __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 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 _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 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(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 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 _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 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 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 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 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 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 _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 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()
def cla(self): super(ParasiteAxes, self).cla() martist.setp(self.get_children(), visible=False) self._get_lines = self._parent_axes._get_lines
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 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