def plot_frame_displacement(realignment_parameters_file, mean_FD_distribution=None, figsize=(11.7, 8.3)): FD_power = calc_frame_dispalcement(realignment_parameters_file) fig = Figure(figsize=figsize) FigureCanvas(fig) if mean_FD_distribution: grid = GridSpec(2, 4) else: grid = GridSpec(1, 4) ax = fig.add_subplot(grid[0, :-1]) ax.plot(FD_power) ax.set_xlim((0, len(FD_power))) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0, -1]) sns.distplot(FD_power, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_FD_distribution: ax = fig.add_subplot(grid[1, :]) sns.distplot(mean_FD_distribution, ax=ax) ax.set_xlabel("Mean Frame Dispalcement (over all subjects) [mm]") MeanFD = FD_power.mean() label = "MeanFD = %g" % MeanFD plot_vline(MeanFD, label, ax=ax) return fig
def plot_mosaic(nifti_file, title=None, overlay_mask=None, figsize=(11.7, 8.3)): if isinstance(nifti_file, str): nii = nb.load(nifti_file) mean_data = nii.get_data() else: mean_data = nifti_file n_images = mean_data.shape[2] row, col = _calc_rows_columns(figsize[0] / figsize[1], n_images) if overlay_mask: overlay_data = nb.load(overlay_mask).get_data() # create figures fig = Figure(figsize=figsize) FigureCanvas(fig) fig.subplots_adjust(top=0.85) for image in (range(n_images)): ax = fig.add_subplot(row, col, image + 1) data_mask = np.logical_not(np.isnan(mean_data)) if overlay_mask: ax.set_rasterized(True) ax.imshow(np.fliplr(mean_data[:, :, image].T), vmin=np.percentile(mean_data[data_mask], 0.5), vmax=np.percentile(mean_data[data_mask], 99.5), cmap=cm.Greys_r, interpolation='nearest', origin='lower') # @UndefinedVariable if overlay_mask: cmap = cm.Reds # @UndefinedVariable cmap._init() alphas = np.linspace(0, 0.75, cmap.N + 3) cmap._lut[:, -1] = alphas ax.imshow(np.fliplr(overlay_data[:, :, image].T), vmin=0, vmax=1, cmap=cmap, interpolation='nearest', origin='lower') # @UndefinedVariable ax.axis('off') fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.01, hspace=0.1) if not title: _, title = os.path.split(nifti_file) title += " (last modified: %s)" % time.ctime( os.path.getmtime(nifti_file)) fig.suptitle(title, fontsize='10') #fig.savefig(output_name) return fig
def plot_fd(fd_file, title='FD plot', mean_fd_dist=None, figsize=(11.7, 8.3)): fd_power = _calc_fd(fd_file) fig = plt.Figure(figsize=figsize) FigureCanvas(fig) if mean_fd_dist: grid = GridSpec(2, 4) else: grid = GridSpec(1, 2, width_ratios=[3, 1]) grid.update(hspace=1.0, right=0.95, left=0.1, bottom=0.2) ax = fig.add_subplot(grid[0, :-1]) ax.plot(fd_power) ax.set_xlim((0, len(fd_power))) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0, -1]) sns.distplot(fd_power, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_fd_dist: ax = fig.add_subplot(grid[1, :]) sns.distplot(mean_fd_dist, ax=ax) ax.set_xlabel("Mean Frame Displacement (over all subjects) [mm]") mean_fd = fd_power.mean() label = r'$\overline{\text{FD}}$ = %g' % mean_fd plot_vline(mean_fd, label, ax=ax) fig.suptitle(title) return fig
def plot_fd(fd_file, fd_radius, mean_fd_dist=None, figsize=DINA4_LANDSCAPE): fd_power = _calc_fd(fd_file, fd_radius) fig = plt.Figure(figsize=figsize) FigureCanvas(fig) if mean_fd_dist: grid = GridSpec(2, 4) else: grid = GridSpec(1, 2, width_ratios=[3, 1]) grid.update(hspace=1.0, right=0.95, left=0.1, bottom=0.2) ax = fig.add_subplot(grid[0, :-1]) ax.plot(fd_power) ax.set_xlim((0, len(fd_power))) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0, -1]) sns.distplot(fd_power, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_fd_dist: ax = fig.add_subplot(grid[1, :]) sns.distplot(mean_fd_dist, ax=ax) ax.set_xlabel("Mean Frame Displacement (over all subjects) [mm]") mean_fd = fd_power.mean() label = r"$\overline{{\text{{FD}}}}$ = {0:g}".format(mean_fd) plot_vline(mean_fd, label, ax=ax) return fig
def plot_dist( main_file, mask_file, xlabel, distribution=None, xlabel2=None, figsize=DINA4_LANDSCAPE, ): data = _get_values_inside_a_mask(main_file, mask_file) fig = plt.Figure(figsize=figsize) FigureCanvas(fig) gsp = GridSpec(2, 1) ax = fig.add_subplot(gsp[0, 0]) sns.distplot(data.astype(np.double), kde=False, bins=100, ax=ax) ax.set_xlabel(xlabel) ax = fig.add_subplot(gsp[1, 0]) sns.distplot(np.array(distribution).astype(np.double), ax=ax) cur_val = np.median(data) label = "{0!g}".format(cur_val) plot_vline(cur_val, label, ax=ax) ax.set_xlabel(xlabel2) return fig
def plot_distrbution_of_values(main_file, mask_file, xlabel, distribution=None, xlabel2=None, figsize=(11.7, 8.3)): data = _get_values_inside_a_mask(main_file, mask_file) fig = Figure(figsize=figsize) FigureCanvas(fig) gs = GridSpec(2, 1) ax = fig.add_subplot(gs[0, 0]) sns.distplot( np.array(data, dtype=np.double), kde=False, bins=100, ax=ax ) #sns.distplot(data.astype(np.double), kde=False, bins=100, ax=ax) ax.set_xlabel(xlabel) ax = fig.add_subplot(gs[1, 0]) sns.distplot( np.array(distribution, dtype=np.double), ax=ax) #sns.distplot(np.array(distribution).astype(np.double), ax=ax) cur_val = np.median(data) label = "%g" % cur_val plot_vline(cur_val, label, ax=ax) ax.set_xlabel(xlabel2) return fig
def plot_frame_displacement(realignment_parameters_file, parameter_source, figsize=(11.7, 8.3)): FD_power = calc_frame_dispalcement(realignment_parameters_file, parameter_source) fig = Figure(figsize=figsize) FigureCanvas(fig) grid = GridSpec(1, 4) ax = fig.add_subplot(grid[0, :-1]) ax.plot(FD_power) ax.set_xlim((0, len(FD_power))) #plot limit of 0.2 mm (which would be used for scrubbing Power 2012) limit = 0.2 * np.ones(np.shape(FD_power)) ax.plot(limit, "red") mean_FD = np.mean(FD_power) maxFD = np.max(FD_power) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0, -1]) sns.distplot(FD_power, vertical=True, ax=ax) ax.set_ylim(ylim) figtitle = 'motion\n mean FD = %.2fmm (>0.5mm exclusion)\n maxFD = %.2fmm (>3mm exclusion)' % ( mean_FD, maxFD) fig.suptitle(figtitle, fontsize='14') return fig
def ree_plot(fn, **kwargs): """ Context manager to create plot with appropriate axes for plotting REE data """ fig = Figure(figsize=kwargs.pop('size', (4, 6))) fig.canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ax.set_yscale('log') yield ax fig.savefig(fn, bbox_inches='tight')
def plotPolygon(tri, polyPoints, nodeID, xRange, yRange): """Plots the voronoi polygon around a single node.""" fig = Figure(figsize=(4,4)) canvas = FigureCanvas(fig) fig.subplots_adjust(left=0.15, bottom=0.13,wspace=0.25, right=0.95) ax = fig.add_subplot(111, aspect='equal') ax.plot(tri.x, tri.y, '.k', ms=1) ax.plot(tri.x[nodeID], tri.y[nodeID],'.r', ms=2) # print polyPoints[nodeID] patch = matplotlib.patches.Polygon(polyPoints[nodeID], closed=True, fill=True, lw=1) ax.add_patch(patch) # ax.plot(tri.x, tri.y, '.k') ax.set_xlim(xRange) ax.set_ylim(yRange) canvas.print_figure("cell", dpi=300.)
def plot_confound(tseries, figsize, name, units=None, series_tr=None, normalize=False): """ A helper function to plot :abbr:`fMRI (functional MRI)` confounds. """ import matplotlib matplotlib.use(config.get('execution', 'matplotlib_backend')) import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas import seaborn as sns fig = plt.Figure(figsize=figsize) FigureCanvas(fig) grid = GridSpec(1, 2, width_ratios=[3, 1], wspace=0.025) grid.update(hspace=1.0, right=0.95, left=0.1, bottom=0.2) ax = fig.add_subplot(grid[0, :-1]) if normalize and series_tr is not None: tseries /= series_tr ax.plot(tseries) ax.set_xlim((0, len(tseries))) ylabel = name if units is not None: ylabel += (' speed [{}/s]' if normalize else ' [{}]').format(units) ax.set_ylabel(ylabel) xlabel = 'Frame #' if series_tr is not None: xlabel = 'Frame # ({} sec TR)'.format(series_tr) ax.set_xlabel(xlabel) ylim = ax.get_ylim() ax = fig.add_subplot(grid[0, -1]) sns.distplot(tseries, vertical=True, ax=ax) ax.set_xlabel('Frames') ax.set_ylim(ylim) ax.set_yticklabels([]) return fig
def plot_frame_displacement(realignment_parameters_file, dvars_file, parameter_source, figsize=(11.7, 8.3)): FD_power = calc_frame_dispalcement(realignment_parameters_file, parameter_source) st_dvars = get_st_dvars(dvars_file) print type(st_dvars) fig = Figure(figsize=figsize) FigureCanvas(fig) grid = GridSpec(4, 4) ax = fig.add_subplot(grid[0:3, 0:3]) ax.plot(FD_power) ax.set_xlim((0, len(FD_power))) #plot limit of 0.2 mm (which would be used for scrubbing Power 2012) limit = 0.2 * np.ones(np.shape(FD_power)) ax.plot(limit, "red") mean_FD = np.mean(FD_power) maxFD = np.max(FD_power) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[3, 0:3]) ax.plot(st_dvars.astype('float')) ax.set_xlim((0, len(st_dvars))) ax.set_ylabel("DVARS [% change BOLD x 10]") ax.set_xlabel("Frame number") maxdvars = np.max(st_dvars.astype('float')) ax = fig.add_subplot(grid[0:3, 3]) sns.distplot(FD_power, vertical=True, axlabel=False, ax=ax) ax.set_ylim(ylim) ax.set_yticklabels('', fontdict=None, minor=False) figtitle = 'motion+signal fluctuations (Power,2012)\n mean FD = %.2fmm (>0.5mm exclusion)\n maxFD = %.2fmm (>3mm exclusion)\n maxDVARS = %.2f pc-change BOLD (>5 exclusion)' % ( mean_FD, maxFD, maxdvars) fig.suptitle(figtitle, fontsize='14') return fig
def plot_textbox(print_text, figsize=(11.7, 8.3)): font = { 'family': 'serif', 'color': 'black', 'weight': 'normal', 'size': 18, } fig = Figure(figsize=figsize) FigureCanvas(fig) grid = GridSpec(1, 1) ax = fig.add_subplot(grid[0, 0]) ax.text(0.5, 0.5, print_text, horizontalalignment='center', verticalalignment='center', fontdict=font) axis('off') return fig
def _plots(self, results, id_): """Create the plots for the report. The report will include all the plots contained in the `~emva1288.process.plotting.EVMA1288plots` list. All plots will be saved in pdf format in the output directory. """ names = {} savedir = os.path.join(self._outdir, id_) try: os.mkdir(savedir) except FileExistsError: # pragma: no cover pass for plt_cls in EVMA1288plots: figure = Figure() _canvas = FigureCanvas(figure) plot = plt_cls(figure) plot.plot(results) plot.rearrange() fname = plt_cls.__name__ + '.pdf' figure.savefig(os.path.join(savedir, fname)) names[plt_cls.__name__] = posixpath.join(id_, fname) return names
def plot_DVARS(title, DVARS_file, mean_DVARS_distribution=None, figsize=(11.7, 8.3)): DVARS = np.loadtxt(DVARS_file) fig = Figure(figsize=figsize) FigureCanvas(fig) if mean_DVARS_distribution: grid = GridSpec(2, 4) else: grid = GridSpec(1, 4) ax = fig.add_subplot(grid[0, :-1]) ax.plot(DVARS) ax.set_xlim((0, len(DVARS))) ax.set_ylabel("DVARS") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0, -1]) sns.distplot(DVARS, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_DVARS_distribution: ax = fig.add_subplot(grid[1, :]) sns.distplot(mean_DVARS_distribution, ax=ax) ax.set_xlabel("Mean DVARS (over all subjects) [std]") MeanFD = DVARS.mean() label = "Mean DVARS = %g" % MeanFD plot_vline(MeanFD, label, ax=ax) fig.suptitle(title, fontsize='14') return fig
def plot_mosaic(nifti_file, title=None, overlay_mask=None, fig=None, bbox_mask_file=None, only_plot_noise=False, vmin=None, vmax=None, figsize=DINA4_LANDSCAPE, cmap='Greys_r', plot_sagittal=True, labels=None): from builtins import bytes, str # pylint: disable=W0622 from matplotlib import cm if isinstance(cmap, (str, bytes)): cmap = cm.get_cmap(cmap) if isinstance(nifti_file, (str, bytes)): nii = nb.as_closest_canonical(nb.load(nifti_file)) mean_data = nii.get_data() mean_data = mean_data[::-1, ...] else: mean_data = nifti_file if bbox_mask_file: bbox_data = nb.as_closest_canonical(nb.load(bbox_mask_file)).get_data() bbox_data = bbox_data[::-1, ...] B = np.argwhere(bbox_data) (ystart, xstart, zstart), (ystop, xstop, zstop) = B.min(0), B.max(0) + 1 mean_data = mean_data[ystart:ystop, xstart:xstop, zstart:zstop] z_vals = np.array(list(range(0, mean_data.shape[2]))) if labels is None: # Reduce the number of slices shown if len(z_vals) > 70: rem = 15 # Crop inferior and posterior if not bbox_mask_file: # mean_data = mean_data[..., rem:-rem] z_vals = z_vals[rem:-rem] else: # mean_data = mean_data[..., 2 * rem:] z_vals = z_vals[2 * rem:] while len(z_vals) > 70: # Discard one every two slices # mean_data = mean_data[..., ::2] z_vals = z_vals[::2] labels = ['%d' % z for z in z_vals] n_images = len(z_vals) row, col = _calc_rows_columns((figsize[0] / figsize[1]), n_images) end = "pre" z_vals = list(z_vals) while (row - 1) * col > len(z_vals) and ( z_vals[0] != 0 or z_vals[-1] != mean_data.shape[2] - 1): if end == "pre": if z_vals[0] != 0: z_vals = [z_vals[0] - 1] + z_vals end = "post" else: if z_vals[-1] != mean_data.shape[2] - 1: z_vals = z_vals + [z_vals[-1] + 1] end = "pre" if (row - 1) * col < len(z_vals): break if overlay_mask: overlay_data = nb.as_closest_canonical( nb.load(overlay_mask)).get_data() # create figures if fig is None: fig = plt.Figure(figsize=figsize) FigureCanvas(fig) est_vmin, est_vmax = get_limits(mean_data, only_plot_noise=only_plot_noise) if not vmin: vmin = est_vmin if not vmax: vmax = est_vmax fig.subplots_adjust(top=0.85) for image, (z_val, z_label) in enumerate(zip(z_vals, labels)): ax = fig.add_subplot(row, col, image + 1) if overlay_mask: ax.set_rasterized(True) ax.imshow(np.fliplr(mean_data[:, :, z_val].T), vmin=vmin, vmax=vmax, cmap=cmap, interpolation='nearest', origin='lower') if overlay_mask: cmap = cm.Reds # @UndefinedVariable cmap._init() alphas = np.linspace(0, 0.75, cmap.N + 3) cmap._lut[:, -1] = alphas ax.imshow(np.fliplr(overlay_data[:, :, z_val].T), vmin=0, vmax=1, cmap=cmap, interpolation='nearest', origin='lower') ax.annotate(z_label, xy=(.99, .99), xycoords='axes fraction', fontsize=8, color='k', backgroundcolor='white', horizontalalignment='right', verticalalignment='top') ax.axis('off') if plot_sagittal: start = int(mean_data.shape[0] / 5) stop = mean_data.shape[0] - start step = int((stop - start) / (col)) x_vals = range(start, stop, step) x_vals = np.array(x_vals[:col]) x_vals += int((stop - x_vals[-1]) / 2) for image, x_val in enumerate(x_vals): ax = fig.add_subplot(row, col, image + (row - 1) * col + 1) ax.imshow(mean_data[x_val, :, :].T, vmin=vmin, vmax=vmax, cmap=cmap, interpolation='nearest', origin='lower') ax.annotate('%d' % x_val, xy=(.99, .99), xycoords='axes fraction', fontsize=8, color='k', backgroundcolor='white', horizontalalignment='right', verticalalignment='top') ax.axis('off') fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.01, hspace=0.1) if title: fig.suptitle(title, fontsize='10') fig.subplots_adjust(wspace=0.002, hspace=0.002) return fig
def montage_tissues_sagittal(overlay_csf, overlay_wm, overlay_gm, underlay, png_name, figsize=(8.3, 11.7)): """ Draws Montage using GM WM and CSF overlays on Anatomical brain in Sagittal Direction Parameters ---------- overlay_csf : string Nifi file CSF MAP overlay_wm : string Nifti file WM MAP overlay_gm : string Nifti file GM MAP underlay : string Nifti for Anatomical Brain png_name : string Proposed name of the montage plot Returns ------- png_name : Path to generated PNG """ def determine_start_and_end(data, direction, percent): x, y, z = data.shape xx1 = 0 xx2 = x - 1 zz1 = 0 zz2 = z - 1 total_non_zero_voxels = len(np.nonzero(data.flatten())[0]) thresh = percent * float(total_non_zero_voxels) start = None end = None if 'axial' in direction: while (zz2 > 0): d = len(np.nonzero(data[:, :, zz2].flatten())[0]) if float(d) > thresh: break zz2 -= 1 while (zz1 < zz2): d = len(np.nonzero(data[:, :, zz1].flatten())[0]) if float(d) > thresh: break zz1 += 1 start = zz1 end = zz2 else: while (xx2 > 0): d = len(np.nonzero(data[xx2, :, :].flatten())[0]) if float(d) > thresh: break xx2 -= 1 while (xx1 < xx2): d = len(np.nonzero(data[xx1, :, :].flatten())[0]) if float(d) > thresh: break xx1 += 1 start = xx1 end = xx2 return start, end def get_spacing(across, down, dimension): space = 10 prod = (across * down * space) if prod > dimension: while (across * down * space) > dimension: space -= 1 else: while (across * down * space) < dimension: space += 1 return space import os import matplotlib import commands # matplotlib.use('Agg') import numpy as np ### try: from mpl_toolkits.axes_grid1 import ImageGrid except: from mpl_toolkits.axes_grid import ImageGrid import matplotlib.pyplot as plt import matplotlib.colors as col import matplotlib.cm as cm import nibabel as nb from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas from matplotlib.figure import Figure Y = nb.load(underlay).get_data() x1, x2 = determine_start_and_end(Y, 'sagittal', 0.0001) spacing = get_spacing(6, 3, x2 - x1) X_csf = nb.load(overlay_csf).get_data() X_wm = nb.load(overlay_wm).get_data() X_gm = nb.load(overlay_gm).get_data() X_csf = X_csf.astype(np.float16) X_wm = X_wm.astype(np.float16) X_gm = X_gm.astype(np.float16) Y = Y.astype(np.float16) max_csf = np.nanmax(np.abs(X_csf.flatten())) X_csf[X_csf != 0.0] = max_csf max_wm = np.nanmax(np.abs(X_wm.flatten())) X_wm[X_wm != 0.0] = max_wm max_gm = np.nanmax(np.abs(X_gm.flatten())) X_gm[X_gm != 0.0] = max_gm x, y, z = Y.shape fig = Figure(figsize=figsize) FigureCanvas(fig) plt.figure(1) max_ = np.max(np.abs(Y)) grid = ImageGrid(fig, 111, nrows_ncols=(3, 6), share_all=True, aspect=True, cbar_mode="None", direction="row") zz = x1 for i in range(6 * 3): if zz >= x2: break im = grid[i].imshow(np.rot90(Y[zz, :, :]), cmap=cm.Greys_r) zz += spacing x, y, z = X_csf.shape X_csf[X_csf == 0.0] = np.nan X_wm[X_wm == 0.0] = np.nan X_gm[X_gm == 0.0] = np.nan print '~~', max_ zz = x1 im = None for i in range(6 * 3): if zz >= x2: break im = grid[i].imshow(np.rot90(X_csf[zz, :, :]), cmap=cm.winter, alpha=0.7, vmin=0, vmax=max_csf) ### im = grid[i].imshow(np.rot90(X_wm[zz, :, :]), cmap=cm.GnBu, alpha=0.7, vmin=0, vmax=max_wm) im = grid[i].imshow(np.rot90(X_gm[zz, :, :]), cmap=cm.bwr, alpha=0.7, vmin=0, vmax=max_gm) grid[i].axes.get_xaxis().set_visible(False) grid[i].axes.get_yaxis().set_visible(False) zz += spacing cbar = grid.cbar_axes[0].colorbar(im) #plt.show() plt.axis("off") png_name = str(os.path.join(os.getcwd(), png_name)) plt.savefig(png_name, dpi=300, bbox_inches='tight') return fig
def plotAllPolygons(tri, polyPoints, xRange, yRange): """docstring for plotAllPolygons""" fig = Figure(figsize=(4,4)) canvas = FigureCanvas(fig) fig.subplots_adjust(left=0.15, bottom=0.13,wspace=0.25, right=0.95) ax = fig.add_subplot(111, aspect='equal') ax.plot(tri.x, tri.y, '.k', ms=2) for nodeID, points in polyPoints.iteritems(): patch = matplotlib.patches.Polygon(points, closed=True, fill=False, lw=1) ax.add_patch(patch) ax.plot(tri.x[tri.hull], tri.y[tri.hull], '.r', ms=3) for edge in tri.edge_db: p1 = (tri.x[edge[0]], tri.y[edge[0]]) p2 = (tri.x[edge[1]], tri.y[edge[1]]) patch = matplotlib.patches.Polygon((p1,p2), lw=0.5, color='g', zOrder=1000) ax.add_patch(patch) pHull = [] for ii in tri.hull: pHull.append((tri.x[ii],tri.y[ii])) patch = matplotlib.patches.Polygon(pHull, closed=True, fill=False, lw=0.8, color='b') ax.add_patch(patch) # for iNode in tri.hull: # print "Lead:" # leadingNode = getLeadingNode(iNode, tri) # pcLead = getCircumcentreOfCommonTriangle(iNode, leadingNode, tri) # print pcLead # pdLead = makeExteriorPoint(iNode, leadingNode, pcLead, tri, xRange, yRange) # print pdLead # # # print "Trail:" # # trailingNode = getTrailingNode(iNode, tri) # # pcTrail = getCircumcentreOfCommonTriangle(iNode, trailingNode, tri) # # pdTrail = makeExteriorPoint(iNode, trailingNode, pcTrail, tri, xRange, yRange) # # # Get coordinates of the two points that define convex hull line seg # p1 = (tri.x[iNode], tri.y[iNode]) # p2 = (tri.x[leadingNode], tri.y[leadingNode]) # # Get slope of that line # m = (p2[1]-p1[1]) / (p2[0]-p1[0]) # # Get perpendicular slope; that of the voronoi cell edge # mPerp = -1./m # print "mPerp plot %.2f" % mPerp # xt = numpy.linspace(min(xRange), max(xRange), 100) # yt = mPerp*(xt-pcLead[0]) + pcLead[1] # ax.plot(xt, yt, '--m') # # # Get the point pi where the voronoi cell line intersects the convex hull line # xi = (pcLead[1]-p1[1] + m*p1[0] - mPerp*pcLead[0]) / (m - mPerp) # yi = m * (xi - p1[0]) + p1[1] # ax.plot([xi], [yi], 'xm', ms=5, zorder=1000) # # ax.plot(tri.x[iNode], tri.y[iNode], 'oy', ms=4, zorder=1000) # ax.plot([pcLead[0]], [pcLead[1]], 'om', ms=5, zorder=1000) # ax.plot([pcLead[0],pdLead[0]], [pcLead[1],pdLead[1]], '-mo') # # ax.plot([pcTrail[0]], [pcTrail[1]], '+c', ms=7, zorder=1100) # break for iNode in xrange(len(tri.x)): patch = matplotlib.patches.Polygon(polyPoints[iNode], closed=True, fill=True, lw=0.5) ax.add_patch(patch) width = xRange[1]-xRange[0] height = yRange[1]-yRange[0] ax.set_xlim(xRange[0]-0.25*width, xRange[1]+0.25*width) ax.set_ylim(yRange[0]-0.25*height, yRange[1]+0.25*height) canvas.print_figure("cell", dpi=300.)
def plot_mosaic(nifti_file, title=None, overlay_mask=None, figsize=(11.7, 8.3)): from six import string_types from pylab import cm if isinstance(nifti_file, string_types): nii = nb.load(nifti_file) mean_data = nii.get_data() else: mean_data = nifti_file z_vals = np.array(range(0, mean_data.shape[2])) # Reduce the number of slices shown if mean_data.shape[2] > 70: rem = 15 # Crop inferior and posterior mean_data = mean_data[..., rem:-rem] z_vals = z_vals[rem:-rem] # Discard one every two slices mean_data = mean_data[..., ::2] z_vals = z_vals[::2] n_images = mean_data.shape[2] row, col = _calc_rows_columns(figsize[0] / figsize[1], n_images) if overlay_mask: overlay_data = nb.load(overlay_mask).get_data() # create figures fig = plt.Figure(figsize=figsize) FigureCanvas(fig) fig.subplots_adjust(top=0.85) for image, z_val in enumerate(z_vals): ax = fig.add_subplot(row, col, image + 1) data_mask = np.logical_not(np.isnan(mean_data)) if overlay_mask: ax.set_rasterized(True) ax.imshow(np.fliplr(mean_data[:, :, image].T), vmin=np.percentile(mean_data[data_mask], 0.5), vmax=np.percentile(mean_data[data_mask], 99.5), cmap=cm.Greys_r, interpolation='nearest', origin='lower') if overlay_mask: cmap = cm.Reds # @UndefinedVariable cmap._init() alphas = np.linspace(0, 0.75, cmap.N + 3) cmap._lut[:, -1] = alphas ax.imshow(np.fliplr(overlay_data[:, :, image].T), vmin=0, vmax=1, cmap=cmap, interpolation='nearest', origin='lower') ax.annotate(str(z_val), xy=(.95, .015), xycoords='axes fraction', fontsize=10, color='white', horizontalalignment='right', verticalalignment='bottom') ax.axis('off') fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.01, hspace=0.1) if not title: _, title = op.split(nifti_file) title += " (last modified: %s)" % time.ctime(op.getmtime(nifti_file)) fig.suptitle(title, fontsize='10') return fig
def main(): if sys.version_info < (3, 2): raise Exception( 'Unsupported Python version, please use at least Python 3.2') args = parse_arguments() ''' This could be done directly from glucometerutils instead of via CSV ''' with open(args.input_file, 'r', newline='') as f: rows = from_csv(f) ''' Skip ketone entries ''' rketones = re.compile('Ketone', flags=re.IGNORECASE) for row in rows: if rketones.search(row.get('measure_method')): rows.remove(row) elif rketones.search(row.get('comment')): rows.remove(row) ''' Skip finger stick test entries ''' rfinger = re.compile('Blood', flags=re.IGNORECASE) if not args.fingerstick: for row in rows: if rfinger.search(row.get('comment')): rows.remove(row) for row in rows: row = parse_entry(row, args.icons) ''' Ensure that the rows are sorted by date ''' rows = sorted(rows, key=lambda row: row.get('date'), reverse=False) ''' Fill in gaps that might exist in the data, in order to smooth the curves and fills ''' ''' We're using 10 minute gaps in order to have more accurate fills ''' rows = fill_gaps(rows, interval=dt.timedelta(minutes=10)) ''' If we're on the default values for units, highs and lows, check that the average value is under 35 (assuming that average mmol/L < 35 and average mg/dL > 35) ''' if args.units == UNIT_MMOLL and (args.high == DEFAULT_HIGH or args.low == DEFAULT_LOW): mean = round(np.mean([l.get('value') for l in rows]), 1) if mean > 35: args.units = UNIT_MGDL args.high = convert_glucose_unit(args.high, UNIT_MMOLL) args.low = convert_glucose_unit(args.low, UNIT_MMOLL) ''' Manually specify max and min for mg/dL ''' args.graph_max = GRAPH_MAX_MGDL args.graph_min = GRAPH_MIN_MGDL ''' Set some defaults ''' rcParams['font.size'] = 8 rcParams['axes.titlesize'] = 12 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = [ 'Calibri', 'Verdana', 'Geneva', 'Arial', 'Helvetica', 'DejaVu Sans', 'Bitstream Vera Sans', 'sans-serif' ] rcParams['mathtext.default'] = 'regular' ''' Load custom fonts for the icon sets At present, backend_pdf does not parse unicode correctly, and unicode characters from many fonts that lack proper glyph names are massed together and printed as the same character. The IcoGluco font, generated from Noto Sans and custom icons on IcoMoon, works around this. ''' if args.icons: args.customfont = import_font('fonts/icogluco.ttf') #args.customfont = import_font('fonts/OpenSansEmoji.ttf') # Alternate font ''' Calculate the days and weeks in which we are interested ''' ''' Note that trim_weeks should be adjusted based on the interval passed to fill_gaps() ''' (days, weeks) = list_days_and_weeks(rows, trim_weeks=300) totalweeks = sum([len(weeks[y]) for y in weeks]) totaldays = len(days) nrows = args.graphs_per_page ncols = 1 plotnum = 1 with FigurePDF(args.output_file) as pdf: ''' Overall averages for all data by hour of the day ''' start = rows[0].get('date') end = rows[-1].get('date') period = start.strftime('%A, %-d %B %Y') + ' to ' + end.strftime( '%A, %-d %B %Y') title = 'Overall Average Glucose Summary for ' + period data = {} for row in rows: mpdate = dt.datetime.combine(rows[0]['date'], row.get('date').time()) data[mdates.date2num(mpdate)] = { 'value': row.get('value'), 'comment': row.get('comment'), } ''' Calculate max and min values for each 15 minute interval across the data set ''' intervals = calculate_max_min(rows) intervaldata = {} for i in intervals: mpdate = dt.datetime.combine(rows[0]['date'], i) intervaldata[mdates.date2num(mpdate)] = { 'max': intervals.get(i).get('max'), 'min': intervals.get(i).get('min'), } ''' Calculate the mean and median blood glucose and HbA1c levels ''' (g_mean, g_median, a_mean, a_median) = calculate_averages(data, args) figure = Figure(figsize=args.pagesize) canvas = FigureCanvas(figure) ax = figure.add_subplot(nrows, ncols, plotnum) ax.set_title(title) figure.set_tight_layout({'pad': 3}) ''' Draw the target range ''' ax.axhspan(args.low, args.high, facecolor='#0072b2', edgecolor='#a8a8a8', alpha=0.1, zorder=15) ''' The maxmin fill (maximum and minimum values for each 15 minute period of the data set, by day) ''' generate_plot( intervaldata, ax=ax, transforms={ 'spline': True, 'maxmin': True }, args=args, color='#979797', ) ''' The graph with a bezier curve applied, and a boundary transform to change line colour above and below the target values ''' generate_plot(data, ax=ax, transforms={'bezier':True, 'avga1c':a_median, \ 'color':[RED, BLUE, RED], 'boundaries':[args.graph_min, args.low, args.high, args.graph_max]}, args=args, color=BLUE, ) ''' Save the graph to the output PDF if we're at the end of the page ''' pdf.savefig(figure) ax.clear() ''' Overall averages for a week by hour of the dday ''' cnt = 0 for year in reversed(sorted(weeks.keys())): for week in reversed(sorted(weeks[year].keys())): ''' Turn the year into a date (the first week of the year is the one containing January 4th) ''' time = dt.datetime.combine(dt.date(year, 1, 4), dt.time(0, 0, 0)) monday = time + dt.timedelta(days=-time.weekday(), weeks=week - 1) sunday = monday + dt.timedelta(days=6) period = monday.strftime( '%A, %-d %B %Y') + ' to ' + sunday.strftime( '%A, %-d %B %Y') title = 'Average Glucose for ' + period weekrows = [] for row in rows: for dow in range(7): day = monday + dt.timedelta(days=dow) if row.get('date').date() == day.date(): weekrows.append(row) data = {} for row in weekrows: mpdate = dt.datetime.combine(monday, row.get('date').time()) data[mdates.date2num(mpdate)] = { 'value': row.get('value'), 'comment': row.get('comment'), } ''' Calculate the maximum and minimum value for each 15-minute period of the day, across the week ''' intervals = calculate_max_min(weekrows) intervaldata = {} for i in intervals: mpdate = dt.datetime.combine(monday.date(), i) intervaldata[mdates.date2num(mpdate)] = { 'max': intervals.get(i).get('max'), 'min': intervals.get(i).get('min'), } ''' Calculate the mean and median blood glucose levels for the week ''' (g_mean, g_median, a_mean, a_median) = calculate_averages(data, args) if cnt % nrows == 0: figure = Figure(figsize=args.pagesize) canvas = FigureCanvas(figure) plotnum = (cnt % nrows) + 1 ax = figure.add_subplot(nrows, ncols, plotnum) ax.set_title(title) figure.set_tight_layout({'pad': 3}) ''' Draw the target range ''' ax.axhspan(args.low, args.high, facecolor='#0072b2', edgecolor='#a8a8a8', alpha=0.1, zorder=15) ''' The maxmin fill of maximum and minimum values ''' generate_plot( intervaldata, ax=ax, transforms={ 'spline': True, 'maxmin': True, 'avga1c': a_median }, args=args, color='#979797', ) ''' The graph with a bezier curve applied, and a boundary transform to change line colour above and below the target values ''' generate_plot(data, ax=ax, transforms={'bezier':True, \ 'color':[RED, BLUE, RED], 'boundaries':[args.graph_min, args.low, args.high, args.graph_max]}, args=args, color=BLUE, ) ''' Save the graph to the output PDF if we're at the end of the page or at the end of the data ''' if (cnt + 1) % nrows == 0 or (cnt + 1) == totalweeks: pdf.savefig(figure) ax.clear() cnt += 1 ''' Daily graphs ''' cnt = 0 for day in reversed(sorted(days.keys())): title = 'Daily Glucose Summary for ' + day.strftime( '%A, %-d %B %Y') data = {} for row in rows: if row.get('date').date() == day.date(): mpdate = dt.datetime.combine(day.date(), row.get('date').time()) data[mdates.date2num(mpdate)] = { 'value': row.get('value'), 'comment': row.get('comment'), } ''' Calculate the mean and median blood glucose levels for the day ''' (g_mean, g_median, a_mean, a_median) = calculate_averages(data, args) if cnt % nrows == 0: figure = Figure(figsize=args.pagesize) canvas = FigureCanvas(figure) plotnum = (cnt % nrows) + 1 ax = figure.add_subplot(nrows, ncols, plotnum) ax.set_title(title) figure.set_tight_layout({'pad': 3}) ''' Draw the target range ''' ax.axhspan(args.low, args.high, facecolor='#0072b2', edgecolor='#a8a8a8', alpha=0.2, zorder=15) ''' Draw graph with a spline tranform and labels ''' generate_plot( data, ax=ax, transforms={ 'spline': True, 'label': True, 'avgglucose': g_median }, args=args, color=BLUE, ) ''' Fill the chart with colour when line is higher or lower than target range ''' generate_plot( data, ax=ax, transforms={ 'spline': True, 'fill': True }, args=args, ) ''' Save the graph to the output PDF if we're at the end of the page ''' if (cnt + 1) % nrows == 0 or (cnt + 1) == totaldays: pdf.savefig(figure) ax.clear() cnt += 1 return 1
import numpy as np # Choose a FigureCanvas from any backend, attach figure to it from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas from matplotlib.figure import Figure def f(t): return np.exp(-t) * np.cos(2 * np.pi * t) t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) # initialize FigureCanvas and attach it to the selected Figure() fig = Figure() canvas = FigureCanvas(fig) # Call Figure method to add subplot, creates Axes ax1 = fig.add_subplot(121) # Use Axes method plot() to plot ax1.plot(t1, f(t1), 'bo', t2, f(t2), 'k') # repeat for second subplot ax2 = fig.add_subplot(122) ax2.plot(t2, np.cos(2 * np.pi * t2), 'r--') # save fig.savefig('pyplot_two_subplots.pdf')
def plot_diffusion_directions(b_images, title=None, overlay_mask=None, figsize=(11.7, 8.3)): if isinstance(b_images, str): nii = nb.load(b_images) data = nii.get_data() else: data = b_images #number of diffusion weighted images n_images = np.shape(data)[3] #plotting the middle slice for each diffusion direction axial_middle = np.shape(data)[2] // 2 row, col = _calc_rows_columns(figsize[0] / figsize[1], n_images) if overlay_mask: overlay_data = nb.load(overlay_mask).get_data() # create figures fig = Figure(figsize=figsize) FigureCanvas(fig) fig.subplots_adjust(top=0.85) for image in (range(n_images)): ax = fig.add_subplot(row, col, image + 1) data_mask = np.logical_not(np.isnan(data)) if overlay_mask: ax.set_rasterized(True) ax.imshow( np.fliplr(data[:, :, axial_middle, image].T), vmin=np.percentile(data[data_mask], 0.6), #0.5 vmax=np.percentile(data[data_mask], 99.5), #99.5 cmap=cm.Greys_r, interpolation='nearest', origin='lower') # @UndefinedVariable if overlay_mask: cmap = cm.Reds # @UndefinedVariable cmap._init() alphas = np.linspace(0, 0.75, cmap.N + 3) cmap._lut[:, -1] = alphas ax.imshow(np.fliplr(overlay_data[:, :, image].T), vmin=0, vmax=1, cmap=cmap, interpolation='nearest', origin='lower') # @UndefinedVariable ax.axis('off') fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.01, hspace=0.1) #if not title: # _, title = os.path.split(b_images) # title += " (last modified: %s)"%time.ctime(os.path.getmtime(b_images)) #fig.suptitle(title, fontsize='14') return fig, n_images
def store_2ddata(data, fname, pltitle='', dir='./', fits=False, plot=True, plrange=(None, None), log=False, rollaxes=False, cmap='RdYlBu', xlab='X [pix]', ylab='Y [pix]', cbarlab=None, hdr=(), ident=True): """ Store **data** to disk as FITS and/or plot as annotated plot in PDF. @param [in] data 2D data array to show @param [in] fname Filename base to use (also fallback for plot title) @param [in] pltitle Plot title (if given) @param [in] dir Output directory @param [in] fits Toggle FITS output @param [in] plot Toggle 2D plot output as PDF @param [in] plrange Use this range for plotting in imshow() (None for autoscale) @param [in] log Take logarithm of data before storing. @param [in] rollaxes Roll axes for PDF plot such that (0,0) is the center @param [in] cmap Colormap to use for PDF @param [in] xlab X-axis label @param [in] ylab Y-axis label @param [in] cbarlab Colorbar label (for units) @param [in] hdr Additional FITS header items, give a list of tuples: [(key1, val1), (key2, val2)] @param [in] ident Add identification string to plots @returns Tuple of (fitsfile path, plotfile path) """ # Do not store empty data if (len(data) <= 0): return data_arr = np.asanyarray(data) if (log): data_arr = np.log10(data_arr) extent = None if (rollaxes): sh = data_arr.shape extent = (-sh[1] / 2., sh[1] / 2., -sh[0] / 2., sh[0] / 2.) # Check if dir exists, or create if (not os.path.isdir(dir)): os.makedirs(dir) fitsfile = filenamify(fname) + '.fits' fitspath = os.path.join(dir, fitsfile) plotfile = filenamify(fname) + '.pdf' plotpath = os.path.join(dir, plotfile) if (fits): # Generate some metadata. Also store plot settings here hdr_dict = dict({ 'filename': fitsfile, 'desc': fname, 'title': pltitle, 'plxlab': xlab, 'plylab': ylab, 'pllog': log, 'plrlxs': rollaxes, 'plcmap': cmap, 'plrng0': plrange[0] if plrange[0] else 0, 'plrng1': plrange[1] if plrange[1] else 0, }.items() + dict(hdr).items()) hdr = mkfitshdr(hdr_dict) # Store data to disk pyfits.writeto(fitspath, data_arr, header=hdr, clobber=True, checksum=True) if (plot): #plot_from_fits(fitspath) pltit = fname if (pltitle): pltit = pltitle # Plot without GUI, using matplotlib internals fig = Figure(figsize=(6, 6)) ax = fig.add_subplot(111) # Make margin smaller fig.subplots_adjust(left=0.15, right=0.95, top=0.9, bottom=0.1) img = 0 # Colormaps # plus min: cmap=cm.get_cmap('RdYlBu') # linear: cmap=cm.get_cmap('YlOrBr') # gray: cmap=cm.get_cmap('gray') img = ax.imshow(data_arr, interpolation='nearest', cmap=cm.get_cmap(cmap), aspect='equal', extent=extent, vmin=plrange[0], vmax=plrange[1]) ax.set_title(pltit) ax.set_xlabel(xlab) ax.set_ylabel(ylab) # dimension 0 is height, dimension 1 is width # When the width is equal or more than the height, use a horizontal bar, otherwise use vertical if (data_arr.shape[0] / data_arr.shape[1] >= 1.0): cbar = fig.colorbar(img, orientation='vertical', aspect=30, pad=0.05, shrink=0.8) else: cbar = fig.colorbar(img, orientation='horizontal', aspect=30, pad=0.12, shrink=0.8) if (cbarlab): cbar.set_label(cbarlab) # Add ID string if (ident): # Make ID string datestr = datetime.datetime.utcnow().isoformat() + 'Z' # Put this in try-except because os.getlogin() fails in screen(1) try: idstr = "%s@%s %s %s" % (os.getlogin(), os.uname()[1], datestr, sys.argv[0]) except OSError: idstr = "%s@%s %s %s" % (getpass.getuser(), os.uname()[1], datestr, sys.argv[0]) ax.text(0.01, 0.01, idstr, fontsize=7, transform=fig.transFigure) canvas = FigureCanvas(fig) #canvas.print_figure(plotfile, bbox_inches='tight') canvas.print_figure(plotpath) return (fitspath, plotpath)
def plot_mosaic(nifti_file, image_type, overlay_mask=None, title=None, figsize=(11.7, 8.3)): if isinstance(nifti_file, str): nii = nb.load(nifti_file) mean_data = nii.get_data() elif isinstance(nifti_file, unicode): nii = nb.load(nifti_file) mean_data = nii.get_data() else: mean_data = nifti_file if image_type == 'flair': n_images = mean_data.shape[0] step = 8 range_plot = np.arange(108, n_images, step) row, col = _calc_rows_columns(figsize[0] / figsize[1], (n_images - 16) / step) #z-direction in flair image is in y-dimension elif image_type == 't1': n_images = mean_data.shape[2] step = 4 range_plot = np.arange(0, n_images - 56, step) row, col = _calc_rows_columns(figsize[0] / figsize[1], (n_images - 56) / step) #z-direction is in z-dimension else: n_images = mean_data.shape[2] step = 1 row, col = _calc_rows_columns(figsize[0] / figsize[1], n_images / step) range_plot = np.arange(0, n_images, step) if overlay_mask: overlay_data = nb.load(overlay_mask).get_data() # create figures fig = Figure(figsize=figsize) FigureCanvas(fig) fig.subplots_adjust(top=0.85) ind = 0 for image in range_plot: ax = fig.add_subplot(row, col, ind + 1) data_mask = np.logical_not(np.isnan(mean_data)) if overlay_mask: ax.set_rasterized(True) if image_type == "flair": #old version of DCM conversion with dcm2nii # ax.imshow(np.flipud(mean_data[50:256,80:256,image].T), vmin=np.percentile(mean_data[data_mask], 0.5), # vmax=np.percentile(mean_data[data_mask],99.5), # cmap=cm.Greys_r, interpolation='nearest', origin='lower') #for new version of DCM conversion with dcm2niix ax.imshow(mean_data[1:216, 1:220, image].T, vmin=np.percentile(mean_data[data_mask], 0.5), vmax=np.percentile(mean_data[data_mask], 99.5), cmap=cm.Greys_r, interpolation='nearest', origin='lower') # @UndefinedVariable elif image_type == "t1": ax.imshow(np.flipud(mean_data[:, :, image].T), vmin=np.percentile(mean_data[data_mask], 0.5), vmax=np.percentile(mean_data[data_mask], 99.5), cmap=cm.Greys_r, interpolation='nearest', origin='lower') # @UndefinedVariable if overlay_mask: cmap = cm.Reds # @UndefinedVariable cmap._init() alphas = np.linspace(0, 0.75, cmap.N + 3) cmap._lut[:, -1] = alphas ax.imshow(np.flipud(overlay_data[:, :, image].T), vmin=0, vmax=1, cmap=cmap, interpolation='nearest', origin='lower') # @UndefinedVariable else: ax.imshow(np.fliplr(mean_data[:, :, image].T), vmin=np.percentile(mean_data[data_mask], 0.5), vmax=np.percentile(mean_data[data_mask], 99.5), cmap=cm.Greys_r, interpolation='nearest', origin='lower') # @UndefinedVariable if overlay_mask: cmap = cm.Reds # @UndefinedVariable cmap._init() alphas = np.linspace(0, 0.75, cmap.N + 3) cmap._lut[:, -1] = alphas ax.imshow(np.fliplr(overlay_data[:, :, image].T), vmin=0, vmax=1, cmap=cmap, interpolation='nearest', origin='lower') # @UndefinedVariable ax.axis('off') ind += 1 fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.01, hspace=0.1) if not title: _, title = os.path.split(nifti_file) title += " (last modified: %s)" % time.ctime( os.path.getmtime(nifti_file)) fig.suptitle(title, fontsize='14') return fig