def create(self, data): """ Does the plotting. """ if len(data[0][1]) != len(data[1][1]): raise ScatterException( 'Number of instances for each competitor must be the same') step = int((self.x_max - self.x_min) / 10) x = np.arange(self.x_min, self.x_max + self.x_min + step, step) # "good" area plt.plot(x, x, color='black', ls=':', lw=1.5, zorder=3) plt.plot(x, 0.1 * x, 'g:', lw=1.5, zorder=3) plt.plot(x, 10 * x, 'g:', lw=1.5, zorder=3) plt.fill_between(x, 0.1 * x, 10 * x, facecolor='green', alpha=0.15, zorder=3) plt.xlim([self.x_min, self.x_max]) plt.ylim([self.y_min, self.y_max]) # timeout lines if self.tol: plt.axvline(self.timeout, linewidth=1, color='red', ls=':', label=str(self.timeout), zorder=3) plt.axhline(self.timeout, linewidth=1, color='red', ls=':', label=str(self.timeout), zorder=3) if self.tlb_loc == 'after': plt.text(2 * self.x_min, self.timeout + self.x_max / 40, self.t_label, horizontalalignment='left', verticalalignment='bottom', fontsize=self.f_props['size'] * 0.8) plt.text(self.timeout + self.x_max / 40, 2 * self.x_min, self.t_label, horizontalalignment='left', verticalalignment='bottom', fontsize=self.f_props['size'] * 0.8, rotation=90) else: plt.text(2 * self.x_min, self.timeout - self.x_max / 3.5, self.t_label, horizontalalignment='left', verticalalignment='bottom', fontsize=self.f_props['size'] * 0.8) plt.text(self.timeout - self.x_max / 3.5, 2 * self.x_min, self.t_label, horizontalalignment='left', verticalalignment='bottom', fontsize=self.f_props['size'] * 0.8, rotation=90) # scatter plt.scatter(data[0][1], data[1][1], c=self.marker_style['color'], marker=self.marker_style['marker'], s=self.marker_style['size'], alpha=self.alpha, zorder=5) # axes' labels if self.x_label: plt.xlabel(self.x_label) else: plt.xlabel(data[0][0]) if self.y_label: plt.ylabel(self.y_label) else: plt.ylabel(data[1][0]) # turning the grid on if not self.no_grid: plt.grid(True, color='black', ls=':', lw=1, zorder=1) # choosing logarithmic scales ax = plt.gca() ax.set_xscale('log') ax.set_yscale('log') # setting ticks font properties # set_*ticklables() seems to be not needed in matplotlib 1.5.0 if float(mpl_version[:3]) < 1.5: ax.set_xticklabels(ax.get_xticks(), self.f_props) ax.set_yticklabels(ax.get_yticks(), self.f_props) # formatter majorFormatter = plt.LogFormatterMathtext(base=10) ax.xaxis.set_major_formatter(majorFormatter) ax.yaxis.set_major_formatter(majorFormatter) # setting frame thickness for i in ax.spines.itervalues(): i.set_linewidth(1) plt.savefig(self.save_to, bbox_inches='tight', transparent=self.transparent)
def create(self, data): """ Does the plotting. """ # making lines coords = [] for d in data: coords.append(np.arange(1, len(d[1]) + 1)) # xs (separate for each line) coords.append(np.array(sorted(d[1]))) lines = plt.plot(*coords, zorder=3) # setting line styles if self.byname == False: # by default, assign fist line to best tool lmap = lambda i: i else: # assign line styles by tool name tnames = [(d[0], i) for i, d in enumerate(data)] tnames.sort(key=lambda pair: pair[0]) tmap = {tn[1]: i for i, tn in enumerate(tnames)} lmap = lambda i: tmap[i] for i, l in enumerate(lines): plt.setp(l, **self.linestyles[lmap(i) % len(self.linestyles)]) # turning the grid on if not self.no_grid: plt.grid(True, color=self.grid_color, ls=self.grid_style, lw=self.grid_width, zorder=1) # axes limits plt.xlim(self.x_min, self.x_max if self.x_max else math.ceil(max([d[2] for d in data]) / float(100)) * 100) plt.ylim(self.y_min, self.y_max if self.y_max else self.timeout) # axes labels if self.x_label: plt.xlabel(self.x_label) else: plt.xlabel('instances') if self.y_label: plt.ylabel(self.y_label) else: plt.ylabel('CPU time (s)') # choosing logarithmic scales if needed ax = plt.gca() if self.x_log: ax.set_xscale('log') if self.y_log: ax.set_yscale('log') # setting ticks # plt.xticks(np.arange(self.x_min, self.x_max + 1, 2)) # if not self.y_log: # # plt.yticks(list(plt.yticks()[0]) + [self.timeout]) # ax.set_yticks(range(0, 2 * (int(self.y_max) if self.y_max else int(self.timeout)), 200)) # setting ticks font properties # set_*ticklables() seems to be not needed in matplotlib 1.5.0 if float(mpl_version[:3]) < 1.5: ax.set_xticklabels(ax.get_xticks(), self.f_props) ax.set_yticklabels(ax.get_yticks(), self.f_props) strFormatter = plt.FormatStrFormatter('%d') logFormatter = plt.LogFormatterMathtext(base=10) ax.xaxis.set_major_formatter(strFormatter if not self.x_log else logFormatter) ax.yaxis.set_major_formatter(strFormatter if not self.y_log else logFormatter) # making the legend if self.lgd_loc != 'off': lgtext = [d[0] for d in data] lg = ax.legend(lines, lgtext, ncol=self.lgd_ncol, loc=self.lgd_loc, fancybox=self.lgd_fancy, shadow=self.lgd_shadow if self.lgd_alpha == 1.0 else False) fr = lg.get_frame() fr.set_lw(1) fr.set_alpha(self.lgd_alpha) fr.set_edgecolor('black') # setting frame thickness for i in six.itervalues(ax.spines): i.set_linewidth(1) plt.savefig(self.save_to, bbox_inches='tight', transparent=self.transparent)
def pdfout(s3d, plane, smoothx=0, smoothy=0, name='', xmin=0, xmax=-1, ymin=0, ymax=-1, errsize=0.5, label=None, vmin=None, vmax=None, ra=None, dec=None, source='', ra2=None, dec2=None, source2='', median=None, axis='WCS', size=(11.5, 9.15), psf=None, cmap='viridis', dy1=0.95, dy2=0.97, twoc=True, norm='lin', fs=24): """ Simple 2d-image plot function Parameters: ---------- plane : np.array Either a 2d array for normal images, or a list of three 2d arrays for an RGB image smoothx, smoothy : integer Integer values of gaussian smoothing for the input plane xmin, xmax, ymin, ymax : integer Zoom into the specific pixel values of the input plane errsize : float Size of error radius with which to highlight a specific region label : str Label of region ra, dec : sexagesimal Location of label label2 : str Label of region 2 ra2, dec2 : sexagesimal Location of label 2 median : integer median filter the input plane axis : string WCS axis or none psf : float FWHM of the PSF which we draw at the left bottom corner of the output cmap : string Color map, default virdis twoc : boolean Write text in image in black and white letters norm : string How to normalize the RGB image (lin, sqrt, log) fs : integer Fontsize (default 24) """ if xmax == -1: xmax = plane.shape[0] if ymax == -1: ymax = plane.shape[1] plane = plane[ymin:ymax, xmin:xmax] if twoc == True: myeffect = withStroke(foreground="w", linewidth=4) kwargs = dict(path_effects=[myeffect]) else: kwargs = {} # hfont = {'fontname':'Helvetica'} if smoothx > 0: plane = blur_image(plane, smoothx, smoothy) if median != None: plane = sp.ndimage.filters.median_filter(plane, median, mode='constant') if ra != None and dec != None: try: posx, posy = s3d.skytopix(ra, dec) except TypeError: posx, posy = s3d.sexatopix(ra, dec) if xmin != 0: posx -= xmin if ymin != 0: posy -= ymin if ra2 != None and dec2 != None: try: posx2, posy2 = s3d.skytopix(ra2, dec2) except TypeError: posx2, posy2 = s3d.sexatopix(ra2, dec2) if xmin != 0: posx2 -= xmin if ymin != 0: posy2 -= ymin if plane.ndim == 2: fig = plt.figure(figsize=size) if fs > 20 and axis == 'WCS': fig.subplots_adjust(bottom=0.22, top=0.99, left=0.12, right=0.96) elif axis == 'WCS': fig.subplots_adjust(bottom=0.20, top=0.99, left=0.08, right=0.96) else: fig.subplots_adjust(bottom=0.005, top=0.995, left=0.005, right=0.94) else: fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(bottom=0.18, top=0.99, left=0.19, right=0.99) ax = fig.add_subplot(1, 1, 1) ax.set_ylim(5, plane.shape[0] - 5) ax.set_xlim(5, plane.shape[1] - 5) if norm == 'lin': plt.imshow( plane, vmin=vmin, vmax=vmax, #extent=[], cmap=cmap, interpolation="nearest") #, aspect="auto")#, cmap='Greys') elif norm == 'log': plt.imshow( plane, vmin=vmin, vmax=vmax, #extent=[], cmap=cmap, norm=LogNorm(), interpolation="nearest") #, aspect="auto")#, cmap='Greys') if plane.ndim == 2: bar = plt.colorbar(shrink=0.9, pad=0.01) if not label == None: bar.set_label(label, size=fs + 15, family='serif') bar.ax.tick_params(labelsize=max(24, fs - 4)) if norm == 'log': bar.formatter = plt.LogFormatterMathtext() labels = [item.get_text() for item in bar.ax.get_yticklabels()] newlab = [] for label in labels: if norm == 'log': newl = label.replace('mathdefault', 'mathrm', 1) else: newl = r'$%s$' % label newlab.append(newl) bar.ax.set_yticklabels(newlab) # bar.update_ticks() if psf != None: psfrad = psf / 2.3538 / s3d.pixsky psfsize = plt.Circle((8 * plane.shape[0] / 9., plane.shape[1] / 9.), psfrad, color='black', alpha=1, **kwargs) ax.add_patch(psfsize) plt.text(8 * plane.shape[0] / 9., plane.shape[0] / 6.5, r'PSF', fontsize=fs, ha='center', va='center', **kwargs) if ra != None and dec != None: psfrad = errsize / 2.3538 / s3d.pixsky psfsize = plt.Circle((posx, posy), psfrad, lw=5, fill=False, color='white', **kwargs) ax.add_patch(psfsize) psfsize = plt.Circle((posx, posy), psfrad, lw=1.5, fill=False, color='black', **kwargs) ax.add_patch(psfsize) plt.text(posx, posy * dy1, source, fontsize=fs, ha='center', va='top', **kwargs) if ra2 != None and dec2 != None: # psfrad = 0.2*errsize/2.3538/s3d.pixsky # psfsize = plt.Circle((posx2,posy2), psfrad, lw=5, fill=False, # color='white', **kwargs) # ax.add_patch(psfsize) # psfsize = plt.Circle((posx2,posy2), psfrad, lw=1.5, fill=False, # color='black', **kwargs) # ax.add_patch(psfsize) print posx2, posy2 ax.plot(posx2 + 1, posy2 + 1, 'o', ms=9, mec='black', c='black') plt.text(posx2, posy2 * dy2, source2, fontsize=fs, ha='center', va='top', **kwargs) if axis == 'WCS': [xticks, xlabels], [yticks, ylabels] = _createaxis(s3d, plane) sel = (xmin + 5 < xticks) * (xmax - 5 > xticks) xticks = xticks[sel] xlabels = xlabels[sel] xticks -= xmin sel = (ymin + 5 < yticks) * (ymax - 5 > yticks) yticks = yticks[sel] ylabels = ylabels[sel] yticks -= ymin plt.xticks(rotation=50) plt.yticks(rotation=50) ax.set_xticks(xticks) ax.set_xticklabels(xlabels, size=fs) ax.set_yticks(yticks) ax.set_yticklabels(ylabels, size=fs) ax.set_xlabel(r'Right Ascension (J2000)', size=fs) ax.set_ylabel(r'Declination (J2000)', size=fs) else: ax.yaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_major_formatter(plt.NullFormatter()) plt.savefig('%s_%s_%s.pdf' % (s3d.inst, s3d.target, name)) plt.close(fig)