def set_alpha(self, alpha): """ Set the alpha transparencies of the collection. Parameters ---------- alpha : float or None """ if alpha is not None: try: float(alpha) except TypeError: raise TypeError('alpha must be a float or None') artist.Artist.set_alpha(self, alpha) try: self._facecolors = mcolors.to_rgba_array( self._facecolors3d, self._alpha) except (AttributeError, TypeError, IndexError): pass try: self._edgecolors = mcolors.to_rgba_array( self._edgecolors3d, self._alpha) except (AttributeError, TypeError, IndexError): pass self.stale = True
def test_conversions_masked(): x1 = np.ma.array(['k', 'b'], mask=[True, False]) x2 = np.ma.array([[0, 0, 0, 1], [0, 0, 1, 1]]) x2[0] = np.ma.masked assert mcolors.to_rgba(x1[0]) == (0, 0, 0, 0) assert_array_equal(mcolors.to_rgba_array(x1), [[0, 0, 0, 0], [0, 0, 1, 1]]) assert_array_equal(mcolors.to_rgba_array(x2), mcolors.to_rgba_array(x1))
def set_alpha(self, alpha): # docstring inherited artist.Artist.set_alpha(self, alpha) try: self._facecolors3d = mcolors.to_rgba_array( self._facecolors3d, self._alpha) except (AttributeError, TypeError, IndexError): pass try: self._edgecolors = mcolors.to_rgba_array( self._edgecolors3d, self._alpha) except (AttributeError, TypeError, IndexError): pass self.stale = True
def test_to_rgba_array_single_str(): # single color name is valid assert_array_equal(mcolors.to_rgba_array("red"), [(1, 0, 0, 1)]) # single char color sequence is deprecated with pytest.warns(cbook.MatplotlibDeprecationWarning, match="Using a string of single character colors as a " "color sequence is deprecated"): array = mcolors.to_rgba_array("rgb") assert_array_equal(array, [(1, 0, 0, 1), (0, 0.5, 0, 1), (0, 0, 1, 1)]) with pytest.raises(ValueError, match="neither a valid single color nor a color " "sequence"): mcolors.to_rgba_array("rgbx")
def do_3d_projection(self, renderer): xs, ys, zs = self._offsets3d vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M) fcs = (zalpha(self._facecolor3d, vzs) if self._depthshade else self._facecolor3d) fcs = mcolors.to_rgba_array(fcs, self._alpha) self.set_facecolors(fcs) ecs = (zalpha(self._edgecolor3d, vzs) if self._depthshade else self._edgecolor3d) ecs = mcolors.to_rgba_array(ecs, self._alpha) self.set_edgecolors(ecs) PathCollection.set_offsets(self, np.column_stack([vxs, vys])) return np.min(vzs) if vzs.size else np.nan
def test_conversions(): # to_rgba_array("none") returns a (0, 4) array. assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4))) # a list of grayscale levels, not a single color. assert_array_equal( mcolors.to_rgba_array([".2", ".5", ".8"]), np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]])) # alpha is properly set. assert mcolors.to_rgba((1, 1, 1), .5) == (1, 1, 1, .5) assert mcolors.to_rgba(".1", .5) == (.1, .1, .1, .5) # builtin round differs between py2 and py3. assert mcolors.to_hex((.7, .7, .7)) == "#b2b2b2" # hex roundtrip. hex_color = "#1234abcd" assert mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True) == \ hex_color
def first_color(colors): if colors is None: return None colors = mcolors.to_rgba_array(colors) if len(colors): return colors[0] else: return "none"
def test_rgba(self): a_masked = np.ma.array([1, 2, 3, np.nan, np.nan, 6], mask=[False, False, True, True, False, False]) a_rgba = mcolors.to_rgba_array(['r', 'g', 'b', 'c', 'm', 'y']) actual = delete_masked_points(a_masked, a_rgba) ind = [0, 1, 5] assert_array_equal(actual[0], a_masked[ind].compressed()) assert_array_equal(actual[1], a_rgba[ind])
def test_cmap_and_norm_from_levels_and_colors2(): levels = [-1, 2, 2.5, 3] colors = ['red', (0, 1, 0), 'blue', (0.5, 0.5, 0.5), (0.0, 0.0, 0.0, 1.0)] clr = mcolors.to_rgba_array(colors) bad = (0.1, 0.1, 0.1, 0.1) no_color = (0.0, 0.0, 0.0, 0.0) masked_value = 'masked_value' # Define the test values which are of interest. # Note: levels are lev[i] <= v < lev[i+1] tests = [('both', None, {-2: clr[0], -1: clr[1], 2: clr[2], 2.25: clr[2], 3: clr[4], 3.5: clr[4], masked_value: bad}), ('min', -1, {-2: clr[0], -1: clr[1], 2: clr[2], 2.25: clr[2], 3: no_color, 3.5: no_color, masked_value: bad}), ('max', -1, {-2: no_color, -1: clr[0], 2: clr[1], 2.25: clr[1], 3: clr[3], 3.5: clr[3], masked_value: bad}), ('neither', -2, {-2: no_color, -1: clr[0], 2: clr[1], 2.25: clr[1], 3: no_color, 3.5: no_color, masked_value: bad}), ] for extend, i1, cases in tests: cmap, norm = mcolors.from_levels_and_colors(levels, colors[0:i1], extend=extend) cmap.set_bad(bad) for d_val, expected_color in cases.items(): if d_val == masked_value: d_val = np.ma.array([1], mask=True) else: d_val = [d_val] assert_array_equal(expected_color, cmap(norm(d_val))[0], 'Wih extend={0!r} and data ' 'value={1!r}'.format(extend, d_val)) with pytest.raises(ValueError): mcolors.from_levels_and_colors(levels, colors)
def test_conversions(): # to_rgba_array("none") returns a (0, 4) array. assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4))) # alpha is properly set. assert_equal(mcolors.to_rgba((1, 1, 1), .5), (1, 1, 1, .5)) # builtin round differs between py2 and py3. assert_equal(mcolors.to_hex((.7, .7, .7)), "#b2b2b2") # hex roundtrip. hex_color = "#1234abcd" assert_equal(mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True), hex_color)
def _zalpha(colors, zs): """Modify the alphas of the color list according to depth.""" # FIXME: This only works well if the points for *zs* are well-spaced # in all three dimensions. Otherwise, at certain orientations, # the min and max zs are very close together. # Should really normalize against the viewing depth. if len(zs) == 0: return np.zeros((0, 4)) norm = Normalize(min(zs), max(zs)) sats = 1 - norm(zs) * 0.7 rgba = np.broadcast_to(mcolors.to_rgba_array(colors), (len(zs), 4)) return np.column_stack([rgba[:, :3], rgba[:, 3] * sats])
def setup_method(self): self.mask1 = [False, False, True, True, False, False] self.arr0 = np.arange(1.0, 7.0) self.arr1 = [1, 2, 3, np.nan, np.nan, 6] self.arr2 = np.array(self.arr1) self.arr3 = np.ma.array(self.arr2, mask=self.mask1) self.arr_s = ['a', 'b', 'c', 'd', 'e', 'f'] self.arr_s2 = np.array(self.arr_s) self.arr_dt = [datetime(2008, 1, 1), datetime(2008, 1, 2), datetime(2008, 1, 3), datetime(2008, 1, 4), datetime(2008, 1, 5), datetime(2008, 1, 6)] self.arr_dt2 = np.array(self.arr_dt) self.arr_colors = ['r', 'g', 'b', 'c', 'm', 'y'] self.arr_rgba = mcolors.to_rgba_array(self.arr_colors)
def setUp(self): self.mask1 = [False, False, True, True, False, False] self.arr0 = np.arange(1.0, 7.0) self.arr1 = [1, 2, 3, np.nan, np.nan, 6] self.arr2 = np.array(self.arr1) self.arr3 = np.ma.array(self.arr2, mask=self.mask1) self.arr_s = ["a", "b", "c", "d", "e", "f"] self.arr_s2 = np.array(self.arr_s) self.arr_dt = [ datetime(2008, 1, 1), datetime(2008, 1, 2), datetime(2008, 1, 3), datetime(2008, 1, 4), datetime(2008, 1, 5), datetime(2008, 1, 6), ] self.arr_dt2 = np.array(self.arr_dt) self.arr_colors = ["r", "g", "b", "c", "m", "y"] self.arr_rgba = mcolors.to_rgba_array(self.arr_colors)
def cmap_2d(shape=(1000, 1000), v=None, alpha=0, plotting=False, diverging=False, diverging_alpha=0.5, rotate=0, flip=False, ax=None): """ Creates a 2 dimensional legend Parameters ---------- shape : list Shape of the returned array v : list, optional If provided it will override the corner colors. It needs to exist of a list of four colors (convertible by to_rgba_array). alpha : float, optional Value between 0 and 1. Default is 0. plotting : bool, optional Plotting cmap. Default is False diverging : bool, optional Apply whitening kernel causing the centre of the cmap to be white if v is left to None. Default is False. diverging_alpha : float, optional The central RGB components are raised with this number. The default is 0.5, which is also the maximum, and will lead to white as the central colors. The minimum is -0.5 which will lead to black as the central color. rotate : int, optional Rotate the created array clockwise. The default is zero. Options are 1, 2 or 3 which will lead to 90, 180 or 270 degrees rotation. flip : bool, optional Flip the array left to right. Default is False. ax : `plt.Axes`, optional matplotlib Axes to plot on. If not provided it is created on the fly. Returns ------- cmap : :obj:`~numpy.ndarray` The created two dimensional legend. Array of dimensions (*shape, 3). RGB configuration Notes ----- For reference see Teuling et al., 2010: "Bivariate colour maps for visualizing climate data" http://iacweb.ethz.ch/doc/publications/2153_ftp.pdf """ if alpha < 0 or alpha > 1: raise ValueError("alpha needs to be between 0 and 1") if type(shape) not in (list, tuple): raise TypeError("shape is expected in the form of a list or tuple") else: if len(shape) != 2: raise ValueError("shape needs to have length 2") else: if shape[0] < 2 or shape[1] < 2: raise ValueError( "shape needs to exist out of positive integers above 1") if type(shape[0]) != int or type(shape[1]) != int: raise TypeError("shape needs to contain two ints") if type(plotting) != bool: raise TypeError("plotting needs to be a boolean") if type(diverging) != bool: raise TypeError("diverging needs to be a boolean") if type(rotate) != int: raise TypeError("rotate should be an integer") if type(flip) != bool: raise TypeError("flip should be a boolean") if isinstance(v, type(None)): v = [0, 0, 0, 0] v[0] = (0, 0.5, 1) # left upper corner v[1] = (1 - alpha, 0, 1 - alpha) # right upper corner v[2] = (1, 0.5, 0) # lower right corner v[3] = (alpha, 1, alpha) # lower left corner corner_colors = np.array(v) corner_colors = np.roll(corner_colors, rotate, axis=0) if flip: corner_colors = np.flipud(corner_colors) else: corner_colors = to_rgba_array(v) cmap = np.empty((*shape, 3)) for i in range(3): cmap[:, :, i] = grid_from_corners(corner_colors[:, i], shape=shape) if diverging: x, y = np.mgrid[-1:1:shape[0] * 1j, -1:1:shape[1] * 1j] cmap += (-diverging_alpha * x**2 / 2 + -diverging_alpha * y**2 / 2 + diverging_alpha)[:, :, np.newaxis] cmap = np.maximum(0, cmap) cmap = np.minimum(1, cmap) if plotting: if type(ax) == type(None): f, ax = plt.subplots(1) ax.imshow(cmap, aspect="auto") ax.set_xticks([]) ax.set_yticks([]) ax.set_title( f"shape : {shape}, alpha : {alpha}, diverging : {diverging}") return cmap
def check_colors(self, part, points, colors, alpha=None): rgba = to_rgba_array(colors, alpha) getter = getattr(points, f"get_{part}colors") assert_array_equal(getter(), rgba)
def structural_plotting(conn_matrix, conn_matrix_symm, label_names, atlas_select, ID, bedpostx_dir, network, parc, plot_switch, coords): import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe import matplotlib.pyplot as plt import seaborn as sns from pynets import plotting as pynplot from matplotlib import colors from nilearn import plotting as niplot edge_threshold = 0.90 connectome_fdt_thresh = 1000 ####Auto-set INPUTS#### try: FSLDIR = os.environ['FSLDIR'] except NameError: print('FSLDIR environment variable not set!') nodif_brain_mask_path = bedpostx_dir + '/nodif_brain_mask.nii.gz' input_MNI = FSLDIR + '/data/standard/MNI152_T1_1mm_brain.nii.gz' if network: probtrackx_output_dir_path = bedpostx_dir + '/probtrackx_' + network else: probtrackx_output_dir_path = bedpostx_dir + '/probtrackx_Whole_brain' dir_path = os.path.dirname(bedpostx_dir) ####Auto-set INPUTS#### if plot_switch == True: plt.figure(figsize=(8, 8)) plt.imshow(conn_matrix, interpolation="nearest", vmax=1, vmin=-1, cmap=plt.cm.RdBu_r) plt.xticks(range(len(label_names)), label_names, size='xx-small', rotation=90) plt.yticks(range(len(label_names)), label_names, size='xx-small') plt_title = atlas_select + ' Structural Connectivity of: ' + str(ID) plt.title(plt_title) plt.grid(False) plt.gcf().subplots_adjust(left=0.8) out_path_fig=dir_path + '/structural_adj_mat_' + str(ID) + '.png' plt.savefig(out_path_fig) plt.close() ##Prepare glass brain figure fdt_paths_loc = probtrackx_output_dir_path + '/fdt_paths.nii.gz' ##Create transform matrix between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'),name='coregister') flirt.inputs.reference = input_MNI flirt.inputs.in_file = nodif_brain_mask_path flirt.inputs.out_matrix_file = bedpostx_dir + '/xfms/diff2MNI.mat' flirt.run() ##Apply transform between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'),name='coregister') flirt.inputs.reference = input_MNI flirt.inputs.in_file = nodif_brain_mask_path flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/diff2MNI.mat' flirt.inputs.out_file = bedpostx_dir + '/xfms/diff2MNI_affine.nii.gz' flirt.run() flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'),name='coregister') flirt.inputs.reference = input_MNI flirt.inputs.in_file = fdt_paths_loc out_file_MNI = fdt_paths_loc.split('.nii')[0] + '_MNI.nii.gz' flirt.inputs.out_file = out_file_MNI flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/diff2MNI.mat' flirt.run() fdt_paths_MNI_loc = probtrackx_output_dir_path + '/fdt_paths_MNI.nii.gz' colors.Normalize(vmin=-1, vmax=1) clust_pal = sns.color_palette("Blues_r", 4) clust_colors = colors.to_rgba_array(clust_pal) ##Plotting with glass brain connectome = niplot.plot_connectome(conn_matrix_symm, coords, edge_threshold=edge_threshold, node_color=clust_colors, edge_cmap=niplot.cm.black_blue_r) connectome.add_overlay(img=fdt_paths_MNI_loc, threshold=connectome_fdt_thresh, cmap=niplot.cm.cyan_copper_r) out_file_path = dir_path + '/structural_connectome_fig_' + network + '_' + str(ID) + '.png' plt.savefig(out_file_path) plt.close() network = network + '_structural' conn_model = 'struct' pynplot.plot_connectogram(conn_matrix, conn_model, atlas_select, dir_path, ID, network, label_names) else: pass return
def _get_colors(c, num): """Stretch the color argument to provide the required number *num*.""" return np.broadcast_to( mcolors.to_rgba_array(c) if len(c) else [0, 0, 0, 0], (num, 4))
def __init__( self, parent, handles, labels, loc=None, numpoints=None, # the number of points in the legend line markerscale=None, # the relative size of legend markers # vs. original markerfirst=True, # controls ordering (left-to-right) of # legend marker and label scatterpoints=None, # number of scatter points scatteryoffsets=None, prop=None, # properties for the legend texts fontsize=None, # keyword to set font size directly labelcolor=None, # keyword to set the text color # spacing & pad defined as a fraction of the font-size borderpad=None, # the whitespace inside the legend border labelspacing=None, # the vertical space between the legend # entries handlelength=None, # the length of the legend handles handleheight=None, # the height of the legend handles handletextpad=None, # the pad between the legend handle # and text borderaxespad=None, # the pad between the axes and legend # border columnspacing=None, # spacing between columns ncol=1, # number of columns mode=None, # mode for horizontal distribution of columns. # None, "expand" fancybox=None, # True use a fancy box, false use a rounded # box, none use rc shadow=None, title=None, # set a title for the legend title_fontsize=None, # the font size for the title framealpha=None, # set frame alpha edgecolor=None, # frame patch edgecolor facecolor=None, # frame patch facecolor bbox_to_anchor=None, # bbox that the legend will be anchored. bbox_transform=None, # transform for the bbox frameon=None, # draw frame handler_map=None, ): """ Parameters ---------- parent : `~matplotlib.axes.Axes` or `.Figure` The artist that contains the legend. handles : list of `.Artist` A list of Artists (lines, patches) to be added to the legend. labels : list of str A list of labels to show next to the artists. The length of handles and labels should be the same. If they are not, they are truncated to the smaller of both lengths. Other Parameters ---------------- %(_legend_kw_doc)s Notes ----- Users can specify any arbitrary location for the legend using the *bbox_to_anchor* keyword argument. *bbox_to_anchor* can be a `.BboxBase` (or derived therefrom) or a tuple of 2 or 4 floats. See `set_bbox_to_anchor` for more detail. The legend location can be specified by setting *loc* with a tuple of 2 floats, which is interpreted as the lower-left corner of the legend in the normalized axes coordinate. """ # local import only to avoid circularity from matplotlib.axes import Axes from matplotlib.figure import Figure super().__init__() if prop is None: if fontsize is not None: self.prop = FontProperties(size=fontsize) else: self.prop = FontProperties( size=mpl.rcParams["legend.fontsize"]) else: self.prop = FontProperties._from_any(prop) if isinstance(prop, dict) and "size" not in prop: self.prop.set_size(mpl.rcParams["legend.fontsize"]) self._fontsize = self.prop.get_size_in_points() self.texts = [] self.legendHandles = [] self._legend_title_box = None #: A dictionary with the extra handler mappings for this Legend #: instance. self._custom_handler_map = handler_map locals_view = locals() for name in [ "numpoints", "markerscale", "shadow", "columnspacing", "scatterpoints", "handleheight", 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad' ]: if locals_view[name] is None: value = mpl.rcParams["legend." + name] else: value = locals_view[name] setattr(self, name, value) del locals_view # trim handles and labels if illegal label... _lab, _hand = [], [] for label, handle in zip(labels, handles): if isinstance(label, str) and label.startswith('_'): cbook._warn_external('The handle {!r} has a label of {!r} ' 'which cannot be automatically added to' ' the legend.'.format(handle, label)) else: _lab.append(label) _hand.append(handle) labels, handles = _lab, _hand handles = list(handles) if len(handles) < 2: ncol = 1 self._ncol = ncol if self.numpoints <= 0: raise ValueError("numpoints must be > 0; it was %d" % numpoints) # introduce y-offset for handles of the scatter plot if scatteryoffsets is None: self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.]) else: self._scatteryoffsets = np.asarray(scatteryoffsets) reps = self.scatterpoints // len(self._scatteryoffsets) + 1 self._scatteryoffsets = np.tile(self._scatteryoffsets, reps)[:self.scatterpoints] # _legend_box is a VPacker instance that contains all # legend items and will be initialized from _init_legend_box() # method. self._legend_box = None if isinstance(parent, Axes): self.isaxes = True self.axes = parent self.set_figure(parent.figure) elif isinstance(parent, Figure): self.isaxes = False self.set_figure(parent) else: raise TypeError("Legend needs either Axes or Figure as parent") self.parent = parent self._loc_used_default = loc is None if loc is None: loc = mpl.rcParams["legend.loc"] if not self.isaxes and loc in [0, 'best']: loc = 'upper right' if isinstance(loc, str): if loc not in self.codes: raise ValueError( "Unrecognized location {!r}. Valid locations are\n\t{}\n". format(loc, '\n\t'.join(self.codes))) else: loc = self.codes[loc] if not self.isaxes and loc == 0: raise ValueError( "Automatic legend placement (loc='best') not implemented for " "figure legend.") self._mode = mode self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) # We use FancyBboxPatch to draw a legend frame. The location # and size of the box will be updated during the drawing time. if facecolor is None: facecolor = mpl.rcParams["legend.facecolor"] if facecolor == 'inherit': facecolor = mpl.rcParams["axes.facecolor"] if edgecolor is None: edgecolor = mpl.rcParams["legend.edgecolor"] if edgecolor == 'inherit': edgecolor = mpl.rcParams["axes.edgecolor"] if fancybox is None: fancybox = mpl.rcParams["legend.fancybox"] self.legendPatch = FancyBboxPatch( xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, # If shadow is used, default to alpha=1 (#8943). alpha=(framealpha if framealpha is not None else 1 if shadow else mpl.rcParams["legend.framealpha"]), # The width and height of the legendPatch will be set (in draw()) # to the length that includes the padding. Thus we set pad=0 here. boxstyle=("round,pad=0,rounding_size=0.2" if fancybox else "square,pad=0"), mutation_scale=self._fontsize, snap=True, visible=(frameon if frameon is not None else mpl.rcParams["legend.frameon"])) self._set_artist_props(self.legendPatch) # init with null renderer self._init_legend_box(handles, labels, markerfirst) tmp = self._loc_used_default self._set_loc(loc) self._loc_used_default = tmp # ignore changes done by _set_loc # figure out title fontsize: if title_fontsize is None: title_fontsize = mpl.rcParams['legend.title_fontsize'] tprop = FontProperties(size=title_fontsize) self.set_title(title, prop=tprop) self._draggable = None # set the text color color_getters = { # getter function depends on line or patch 'linecolor': ['get_color', 'get_facecolor'], 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'], 'mfc': ['get_markerfacecolor', 'get_facecolor'], 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'], 'mec': ['get_markeredgecolor', 'get_edgecolor'], } if labelcolor is None: pass elif isinstance(labelcolor, str) and labelcolor in color_getters: getter_names = color_getters[labelcolor] for handle, text in zip(self.legendHandles, self.texts): for getter_name in getter_names: try: color = getattr(handle, getter_name)() text.set_color(color) break except AttributeError: pass elif np.iterable(labelcolor): for text, color in zip( self.texts, itertools.cycle(colors.to_rgba_array(labelcolor))): text.set_color(color) else: raise ValueError("Invalid argument for labelcolor : %s" % str(labelcolor))
def _is_light(color): """Determines if a color (or each of a sequence of colors) is light (as opposed to dark). Based on ITU BT.601 luminance formula (see https://stackoverflow.com/a/596241).""" rgbaArr = colors.to_rgba_array(color) return rgbaArr[:, :3].dot((.299, .587, .114)) > .5
def test_color_logic(pcfunc): z = np.arange(12).reshape(3, 4) # Explicitly set an edgecolor. pc = pcfunc(z, edgecolors='red', facecolors='none') pc.update_scalarmappable() # This is called in draw(). # Define 2 reference "colors" here for multiple use. face_default = mcolors.to_rgba_array(pc._get_default_facecolor()) mapped = pc.get_cmap()(pc.norm((z.ravel()))) # Github issue #1302: assert mcolors.same_color(pc.get_edgecolor(), 'red') # Check setting attributes after initialization: pc = pcfunc(z) pc.set_facecolor('none') pc.set_edgecolor('red') pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), 'none') assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) pc.set_alpha(0.5) pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]]) pc.set_alpha(None) # restore default alpha pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Reset edgecolor to default. pc.set_edgecolor(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), mapped) pc.set_facecolor(None) # restore default for facecolor pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), 'none') # Turn off colormapping entirely: pc.set_array(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), 'none') assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped # Turn it back on by restoring the array (must be 1D!): pc.set_array(z.ravel()) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), 'none') # Give color via tuple rather than string. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0)) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Provide an RGB array; mapping overrides it. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3))) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Turn off the mapping. pc.set_array(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3))) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # And an RGBA array. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4))) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Turn off the mapping. pc.set_array(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4))) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
def add_model_surfaces(self, faults=True, cmap=None, fault_colour='black', **kwargs): """Add surfaces for all of the interfaces in the model Parameters ---------- faults : bool, optional whether to draw faults, by default True cmap : string matplotlib cmap Notes ------ Other parameters are passed to self.add_isosurface() """ from matplotlib import cm from matplotlib import colors n_units = 0 #count how many discrete colours for g in self.model.stratigraphic_column.keys(): for u in self.model.stratigraphic_column[g].keys(): n_units += 1 if cmap is None: colours = [] boundaries = [] data = [] for g in self.model.stratigraphic_column.keys(): if g == 'faults': # skip anything saved in faults here continue for u, v in self.model.stratigraphic_column[g].items(): data.append((v['id'], v['colour'])) colours.append(v['colour']) boundaries.append(v['id']) cmap = colors.ListedColormap(colours) else: cmap = cm.get_cmap(cmap, n_units) ci = 0 cmap_colours = colors.to_rgba_array(cmap.colors) for g in self.model.stratigraphic_column.keys(): if g in self.model.feature_name_index: feature = self.model.features[self.model.feature_name_index[g]] names = [] values = [] colours = [] for u, vals in self.model.stratigraphic_column[g].items(): names.append(u) values.append(vals['min']) colours.append(cmap_colours[ci, :]) ci += 1 self.add_isosurface(feature, slices=values, names=names, colours=colours, **kwargs) if faults: for f in self.model.features: if f.type == 'fault': def mask(x): val = f.displacementfeature.evaluate_value(x) val[np.isnan(val)] = 0 maskv = np.zeros(val.shape).astype(bool) maskv[np.abs(val) > 0.001] = 1 return maskv if f.name in self.model.stratigraphic_column['faults']: fault_colour = self.model.stratigraphic_column[ 'faults'][f.name].get('colour', ['red']) # print(fault_colour) # if fault_colour != None: # fault_colour = colors.to_rgba(fault_colour[0]) # print(fault_color) region = kwargs.pop('region', None) self.add_isosurface(f, isovalue=0, region=mask, colour=fault_colour[0], **kwargs)
[[1.0, .0], [.0, 1.0]], ] pis = [.15, .2, .5, .15] N = [] for mu, sig in zip(mus, sigs): N.append(multivariate_normal(mean=mu, cov=sig)) # Sample n_samples = 20000 samples = np.concatenate( [n.rvs(int(n_samples * pi)) for pi, n in zip(pis, N)]) # GMM gmm = GaussianMixture(4) gmm.fit(samples) # Plotting LiCmap = ListedColormap(["r", "b", "g", "k"]) fig, ax = plt.subplots(ncols=2, nrows=1) # Left Plot ax[0].scatter(*samples.T, s=1, c=gmm.predict(samples), cmap=LiCmap) # Right Plot for cls, c in zip(range(4), LiCmap.colors): rgba = np.repeat(to_rgba_array(c), samples.shape[0], axis=0) rgba[:, 3] = gmm.predict_proba(samples).T[cls] ax[1].scatter(*samples.T, color=rgba, s=1) plt.savefig("./results/2-15-soft-clustring.png")
def plot_khat(khats, color=None, xlabels=False, show_bins=False, bin_format="{1:.1f}%", annotate=False, hover_label=False, figsize=None, textsize=None, coords=None, legend=False, markersize=None, ax=None, hlines_kwargs=None, **kwargs): """ Plot Pareto tail indices. Parameters ---------- khats : ELPDData cointaining pareto shapes information or array Pareto tail indices. color : str or array_like, optional Colors of the scatter plot, if color is a str all dots will have the same color, if it is the size of the observations, each dot will have the specified color, otherwise, it will be interpreted as a list of the dims to be used for the color code xlabels : bool, optional Use coords as xticklabels show_bins : bool, optional Show the number of khats which fall in each bin. bin_format : str, optional The string is used as formatting guide calling ``show_bins.format(count, pct)``. annotate : bool, optional Show the labels of k values larger than 1. hover_label : bool, optional Show the datapoint label when hovering over it with the mouse. Requires an interactive backend. figsize : tuple, optional Figure size. If None it will be defined automatically. textsize: float, optional Text size scaling factor for labels, titles and lines. If None it will be autoscaled based on figsize. coords : mapping, optional Coordinates of points to plot. **All** values are used for computation, but only a a subset can be plotted for convenience. legend : bool, optional Include a legend to the plot. Only taken into account when color argument is a dim name. markersize: int, optional markersize for scatter plot. Defaults to `None` in which case it will be chosen based on autoscaling for figsize. ax: axes, optional Matplotlib axes hlines_kwargs: dictionary, optional Additional keywords passed to ax.hlines kwargs : Additional keywords passed to ax.scatter Returns ------- ax : axes Matplotlib axes. Examples -------- Plot estimated pareto shape parameters showing how many fall in each category. .. plot:: :context: close-figs >>> import arviz as az >>> radon = az.load_arviz_data("radon") >>> loo_radon = az.loo(radon, pointwise=True) >>> az.plot_khat(loo_radon, show_bins=True) Show xlabels .. plot:: :context: close-figs >>> centered_eight = az.load_arviz_data("centered_eight") >>> khats = az.loo(centered_eight, pointwise=True).pareto_k >>> az.plot_khat(khats, xlabels=True, annotate=True) Use coord values to create color mapping .. plot:: :context: close-figs >>> az.plot_khat(loo_radon, color="observed_county", cmap="tab20") Use custom color scheme .. plot:: :context: close-figs >>> counties = radon.posterior.observed_county.values >>> colors = [ ... "blue" if county[-1] in ("A", "N") else "green" for county in counties ... ] >>> az.plot_khat(loo_radon, color=colors) """ if hover_label and mpl.get_backend() not in mpl.rcsetup.interactive_bk: hover_label = False warnings.warn( "hover labels are only available with interactive backends. To switch to an " "interactive backend from ipython or jupyter, use `%matplotlib` there should be " "no need to restart the kernel. For other cases, see " "https://matplotlib.org/3.1.0/tutorials/introductory/usage.html#backends", UserWarning, ) if hlines_kwargs is None: hlines_kwargs = {} hlines_kwargs.setdefault("linestyle", [":", "-.", "--", "-"]) hlines_kwargs.setdefault("alpha", 0.7) hlines_kwargs.setdefault("zorder", -1) hlines_kwargs.setdefault("color", "C1") if coords is None: coords = {} if color is None: color = "C0" if isinstance(khats, np.ndarray): khats = khats.flatten() xlabels = False legend = False dims = [] else: if isinstance(khats, ELPDData): khats = khats.pareto_k if not isinstance(khats, DataArray): raise ValueError( "Incorrect khat data input. Check the documentation") khats = get_coords(khats, coords) dims = khats.dims n_data_points = khats.size xdata = np.arange(n_data_points) if isinstance(khats, DataArray): coord_labels = format_coords_as_labels(khats) else: coord_labels = xdata.astype(str) (figsize, ax_labelsize, _, xt_labelsize, linewidth, scaled_markersize) = _scale_fig_size(figsize, textsize) if markersize is None: markersize = scaled_markersize**2 # s in scatter plot mus be markersize square # for dots to have the same size kwargs.setdefault("s", markersize) kwargs.setdefault("marker", "+") if isinstance(color, str): if color in dims: colors, color_mapping = color_from_dim(khats, color) cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) rgba_c = cmap(colors) else: legend = False rgba_c = to_rgba_array(np.full(n_data_points, color)) else: legend = False try: rgba_c = to_rgba_array(color) except ValueError: cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) rgba_c = cmap(color) if ax is None: fig, ax = plt.subplots(figsize=figsize, constrained_layout=not xlabels) else: fig = ax.get_figure() khats = khats if isinstance(khats, np.ndarray) else khats.values.flatten() alphas = 0.5 + 0.2 * (khats > 0.5) + 0.3 * (khats > 1) rgba_c[:, 3] = alphas sc_plot = ax.scatter(xdata, khats, c=rgba_c, **kwargs) if annotate: idxs = xdata[khats > 1] for idx in idxs: ax.text( idx, khats[idx], coord_labels[idx], horizontalalignment="center", verticalalignment="bottom", fontsize=0.8 * xt_labelsize, ) xmin, xmax = ax.get_xlim() if show_bins: xmax += n_data_points / 12 ylims1 = ax.get_ylim() ax.hlines([0, 0.5, 0.7, 1], xmin=xmin, xmax=xmax, linewidth=linewidth, **hlines_kwargs) ylims2 = ax.get_ylim() ymin = min(ylims1[0], ylims2[0]) ymax = min(ylims1[1], ylims2[1]) if show_bins: bin_edges = np.array([ymin, 0.5, 0.7, 1, ymax]) bin_edges = bin_edges[(bin_edges >= ymin) & (bin_edges <= ymax)] hist, _ = np.histogram(khats, bin_edges) for idx, count in enumerate(hist): ax.text( (n_data_points - 1 + xmax) / 2, np.mean(bin_edges[idx:idx + 2]), bin_format.format(count, count / n_data_points * 100), horizontalalignment="center", verticalalignment="center", ) ax.set_ylim(ymin, ymax) ax.set_xlim(xmin, xmax) ax.set_xlabel("Data Point", fontsize=ax_labelsize) ax.set_ylabel(r"Shape parameter k", fontsize=ax_labelsize) ax.tick_params(labelsize=xt_labelsize) if xlabels: set_xticklabels(ax, coord_labels) fig.autofmt_xdate() fig.tight_layout() if legend: ncols = len(color_mapping) // 6 + 1 for label, float_color in color_mapping.items(): ax.scatter([], [], c=[cmap(float_color)], label=label, **kwargs) ax.legend(ncol=ncols, title=color) if hover_label and mpl.get_backend() in mpl.rcsetup.interactive_bk: _make_hover_annotation(fig, ax, sc_plot, coord_labels, rgba_c) return ax
if hex_value: # This section of code iterates over the every pixel in the image, # and converts its color to an rgb tuple. It will then calculate the # euclidean distance (https://en.wikipedia.org/wiki/Euclidean_distance) # of all of the colors and set the color of the pixel to be the color with the # shortest distance. I'm not knowledgeable on color theory, but this is the best # way to reduce colors that I could think of. As I learn more, I will create a less # intensive, more efficient algorithm. for x in range(im.size[1]): for y in range(im.size[0]): minColorDistance = -1 minColor = None pixel = px[x, y] for color in colors: rgb = to_rgba_array(color)[0] for i, val in enumerate(rgb): rgb[i] = int(val * 255) distance = sqrt((pixel[0] - rgb[0])**2 + (pixel[1] - rgb[1])**2 + (pixel[2] - rgb[2])**2) if minColorDistance == -1: minColorDistance = distance minColor = rgb else: if minColorDistance > distance: minColorDistance = distance minColor = rgb px[x, y] = (int(minColor[0]), int(minColor[1]), int(minColor[2]))
def _maybe_depth_shade_and_sort_colors(self, color_array): color_array = (_zalpha(color_array, self._vzs) if self._vzs is not None and self._depthshade else color_array) if len(color_array) > 1: color_array = color_array[self._z_markers_idx] return mcolors.to_rgba_array(color_array, self._alpha)
def plot_khat( hover_label, # pylint: disable=unused-argument hover_format, # pylint: disable=unused-argument ax, figsize, xdata, khats, kwargs, threshold, coord_labels, show_hlines, show_bins, hlines_kwargs, xlabels, # pylint: disable=unused-argument legend, # pylint: disable=unused-argument color, dims, textsize, markersize, # pylint: disable=unused-argument n_data_points, bin_format, backend_kwargs, show, ): """Bokeh khat plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ), **backend_kwargs, } (figsize, *_, line_width, _) = _scale_fig_size(figsize, textsize) if hlines_kwargs is None: hlines_kwargs = {} hlines_kwargs.setdefault("hlines", [0, 0.5, 0.7, 1]) cmap = None if isinstance(color, str): if color in dims: colors, _ = color_from_dim(khats, color) cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) rgba_c = cmap(colors) else: legend = False rgba_c = to_rgba_array(np.full(n_data_points, color)) else: legend = False try: rgba_c = to_rgba_array(color) except ValueError: cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) rgba_c = cmap(color) khats = khats if isinstance(khats, np.ndarray) else khats.values.flatten() alphas = 0.5 + 0.2 * (khats > 0.5) + 0.3 * (khats > 1) rgba_c = vectorized_to_hex(rgba_c) if ax is None: ax = create_axes_grid( 1, figsize=figsize, squeeze=True, backend_kwargs=backend_kwargs, ) if not isinstance(rgba_c, str) and isinstance(rgba_c, Iterable): for idx, (alpha, rgba_c_) in enumerate(zip(alphas, rgba_c)): ax.cross( xdata[idx], khats[idx], line_color=rgba_c_, fill_color=rgba_c_, line_alpha=alpha, fill_alpha=alpha, size=10, ) else: ax.cross( xdata, khats, line_color=rgba_c, fill_color=rgba_c, size=10, line_alpha=alphas, fill_alpha=alphas, ) if threshold is not None: idxs = xdata[khats > threshold] for idx in idxs: ax.text(x=[idx], y=[khats[idx]], text=[coord_labels[idx]]) if show_hlines: for hline in hlines_kwargs.pop("hlines"): _hline = Span( location=hline, dimension="width", line_color="grey", line_width=line_width, line_dash="dashed", ) ax.renderers.append(_hline) ymin = min(khats) ymax = max(khats) xmax = len(khats) if show_bins: bin_edges = np.array([ymin, 0.5, 0.7, 1, ymax]) bin_edges = bin_edges[(bin_edges >= ymin) & (bin_edges <= ymax)] hist, _, _ = histogram(khats, bin_edges) for idx, count in enumerate(hist): ax.text( x=[(n_data_points - 1 + xmax) / 2], y=[np.mean(bin_edges[idx:idx + 2])], text=[bin_format.format(count, count / n_data_points * 100)], ) ax.x_range._property_values["end"] = xmax + 1 # pylint: disable=protected-access ax.xaxis.axis_label = "Data Point" ax.yaxis.axis_label = "Shape parameter k" if ymin > 0: ax.y_range._property_values["start"] = -0.02 # pylint: disable=protected-access if ymax < 1: ax.y_range._property_values["end"] = 1.02 # pylint: disable=protected-access elif ymax > 1 & threshold: ax.y_range._property_values["end"] = 1.1 * ymax # pylint: disable=protected-access show_layout(ax, show) return ax
def import_mat_func(input_file, ID, atlas_select, NETWORK, pynets_dir, node_size, mask, thr, graph, parlistfile, sps_model, all_nets): if '.nii' in input_file and parlistfile == None and NETWORK == None: if graph == False: func_file = input_file if all_nets != None: func_img = nib.load(func_file) par_path = pynets_dir + '/RSN_refs/yeo.nii.gz' par_img = nib.load(par_path) par_data = par_img.get_data() ref_dict = { 0: 'unknown', 1: 'VIS', 2: 'SM', 3: 'DA', 4: 'VA', 5: 'LIM', 6: 'FP', 7: 'DEF' } def get_ref_net(x, y, z): aff_inv = npl.inv(func_img.affine) # apply_affine(aff, (x,y,z)) # vox to mni vox_coord = apply_affine(aff_inv, (x, y, z)) # mni to vox return ref_dict[int(par_data[int(vox_coord[0]), int(vox_coord[1]), int(vox_coord[2])])] dir_path = os.path.dirname(os.path.realpath(func_file)) atlas = getattr(datasets, 'fetch_%s' % atlas_select)() atlas_name = atlas['description'].splitlines()[0] print(atlas_name + ' comes with {0}.'.format(atlas.keys())) print("\n") coords = np.vstack( (atlas.rois['x'], atlas.rois['y'], atlas.rois['z'])).T if all_nets != None: membership = pd.Series([ get_ref_net(coord[0], coord[1], coord[2]) for coord in coords ]) print('Stacked atlas coordinates in array of shape {0}.'.format( coords.shape)) print("\n") if mask is not None: from nilearn import masking mask_data, _ = masking._load_mask_img(mask) mask_coords = list(zip(*np.where(mask_data != 0))) for coord in coords: if tuple(coord) not in mask_coords: print('Removing coordinate: ' + str(tuple(coord)) + ' since it falls outside of network mask...') ix = np.where(coords == coord)[0][0] coords = np.delete(coords, ix, axis=0) print(str(len(coords))) print("\n") spheres_masker = input_data.NiftiSpheresMasker( seeds=coords, radius=float(node_size), memory='nilearn_cache', memory_level=5, verbose=2) time_series = spheres_masker.fit_transform(func_file) correlation_measure = ConnectivityMeasure(kind='correlation') correlation_matrix = correlation_measure.fit_transform( [time_series])[0] print("\n") print('Time series has {0} samples'.format(time_series.shape[0])) print("\n") else: correlation_matrix = genfromtxt(graph, delimiter='\t') plt.imshow(correlation_matrix, vmin=-1., vmax=1., cmap='RdBu_r', interpolation='nearest') plt.colorbar() plt.title(atlas_name + ' correlation matrix') out_path_fig = dir_path + '/' + ID + '_' + atlas_name + '_adj_mat_corr.png' plt.savefig(out_path_fig) plt.close() ##Tweak edge_threshold to keep only the strongest connections. atlast_graph_title = atlas_name + ' correlation graph' if mask is None: atlast_graph_title = atlas_name + ' correlation graph' else: atlast_graph_title = atlas_name + ' Masked Nodes' edge_threshold = str(float(thr) * 100) + '%' # plot graph: if all_nets != None: # coloring code: n = len(membership.unique()) clust_pal = sns.color_palette("Set1", n) clust_lut = dict( zip(map(str, np.unique(membership.astype('category'))), clust_pal)) clust_colors = colors.to_rgba_array(membership.map(clust_lut)) plotting.plot_connectome(correlation_matrix, coords, node_color=clust_colors, title=atlast_graph_title, edge_threshold=edge_threshold, node_size=20, colorbar=True) else: plotting.plot_connectome(correlation_matrix, coords, title=atlast_graph_title, edge_threshold=edge_threshold, node_size=20, colorbar=True) out_path_fig = dir_path + '/' + ID + '_' + atlas_name + '_connectome_viz.png' plt.savefig(out_path_fig) plt.close() time_series_path = dir_path + '/' + ID + '_ts.txt' np.savetxt(time_series_path, time_series, delimiter='\t') mx = genfromtxt(time_series_path, delimiter='') elif '.nii' in input_file and parlistfile != None and NETWORK == None: # block of code for whole brain parcellations if all_nets != None: par_path = pynets_dir + '/RSN_refs/yeo.nii.gz' par_img = nib.load(par_path) par_data = par_img.get_data() ref_dict = { 0: 'unknown', 1: 'VIS', 2: 'SM', 3: 'DA', 4: 'VA', 5: 'LIM', 6: 'FP', 7: 'DEF' } def get_ref_net(x, y, z): aff_inv = npl.inv(bna_img.affine) # apply_affine(aff, (x,y,z)) # vox to mni vox_coord = apply_affine(aff_inv, (x, y, z)) # mni to vox return ref_dict[int(par_data[int(vox_coord[0]), int(vox_coord[1]), int(vox_coord[2])])] func_file = input_file dir_path = os.path.dirname(os.path.realpath(func_file)) atlas_name = parlistfile.split('/')[-1].split('.')[0] # Code for getting name and coordinates of parcels. # Adapted from Dan L. (https://github.com/danlurie/despolab_lesion/blob/master/code/sandbox/Sandbox%20-%20Calculate%20and%20plot%20HCP%20mean%20matrix.ipynb) bna_img = nib.load(parlistfile) bna_data = bna_img.get_data() if bna_img.get_data_dtype() != np.dtype(np.int): bna_data_for_coords = bna_img.get_data() # Number of parcels: par_max = np.ceil(np.max(bna_data_for_coords)).astype('int') bna_data = bna_data.astype('int16') else: par_max = np.max(bna_data) img_stack = [] for idx in range(1, par_max + 1): roi_img = bna_data == idx img_stack.append(roi_img) img_stack = np.array(img_stack) img_list = [] for idx in range(par_max): roi_img = nilearn.image.new_img_like(bna_img, img_stack[idx]) img_list.append(roi_img) bna_4D = nilearn.image.concat_imgs(img_list) coords = [] for roi_img in img_list: coords.append(nilearn.plotting.find_xyz_cut_coords(roi_img)) coords = np.array(coords) if all_nets != None: membership = pd.Series([ get_ref_net(coord[0], coord[1], coord[2]) for coord in coords ]) # atlas = getattr(datasets, 'fetch_%s' % atlas_select)() # atlas_name = atlas['description'].splitlines()[0] print("\n") print(atlas_name + ' comes with {0}.'.format(par_max) + 'parcels') print("\n") print("\n") print('Stacked atlas coordinates in array of shape {0}.'.format( coords.shape)) print("\n") if mask is not None: from nilearn import masking mask_data, _ = masking._load_mask_img(mask) mask_coords = list(zip(*np.where(mask_data != 0))) for coord in coords: if tuple(coord) not in mask_coords: print('Removing coordinate: ' + str(tuple(coord)) + ' since it falls outside of network mask...') ix = np.where(coords == coord)[0][0] coords = np.delete(coords, ix, axis=0) print(str(len(coords))) ##extract time series from whole brain parcellaions: parcellation = nib.load(parlistfile) parcel_masker = input_data.NiftiLabelsMasker(labels_img=parcellation, background_label=0, memory='nilearn_cache', memory_level=5) time_series = parcel_masker.fit_transform(func_file) ##old ref code for coordinate parcellations: #spheres_masker = input_data.NiftiSpheresMasker(seeds=coords, radius=float(node_size), memory='nilearn_cache', memory_level=2, verbose=2) #time_series = spheres_masker.fit_transform(func_file) correlation_measure = ConnectivityMeasure(kind='correlation') correlation_matrix = correlation_measure.fit_transform([time_series ])[0] print("\n") print('Time series has {0} samples'.format(time_series.shape[0])) print("\n") plt.imshow(correlation_matrix, vmin=-1., vmax=1., cmap='RdBu_r', interpolation='nearest') plt.colorbar() plt.title(atlas_name + ' correlation matrix') out_path_fig = dir_path + '/' + ID + '_' + atlas_name + '_adj_mat_corr.png' plt.savefig(out_path_fig) plt.close() ##Tweak edge_threshold to keep only the strongest connections. atlast_graph_title = atlas_name + ' correlation graph' if mask is None: atlast_graph_title = atlas_name + ' correlation graph' else: atlast_graph_title = atlas_name + ' Masked Nodes' edge_threshold = str(float(thr) * 100) + '%' if all_nets != None: # coloring code: n = len(membership.unique()) clust_pal = sns.color_palette("Set1", n) clust_lut = dict( zip(map(str, np.unique(membership.astype('category'))), clust_pal)) clust_colors = colors.to_rgba_array(membership.map(clust_lut)) plotting.plot_connectome(correlation_matrix, coords, node_color=clust_colors, title=atlast_graph_title, edge_threshold=edge_threshold, node_size=20, colorbar=True) else: plotting.plot_connectome(correlation_matrix, coords, title=atlast_graph_title, edge_threshold=edge_threshold, node_size=20, colorbar=True) out_path_fig = dir_path + '/' + ID + '_' + atlas_name + '_connectome_viz.png' plt.savefig(out_path_fig) plt.close() time_series_path = dir_path + '/' + ID + '_ts.txt' np.savetxt(time_series_path, time_series, delimiter='\t') mx = genfromtxt(time_series_path, delimiter='') elif '.nii' in input_file and NETWORK != None: func_file = input_file ##Reference RSN list load_path = pynets_dir + '/RSN_refs/' + NETWORK + '_coords.csv' df = pd.read_csv(load_path).ix[:, 0:4] i = 1 coords = [] labels = [] for i in range(len(df)): print("ROI Reference #: " + str(i)) x = int(df.ix[i, 1]) y = int(df.ix[i, 2]) z = int(df.ix[i, 3]) print("X:" + str(x) + " Y:" + str(y) + " Z:" + str(z)) coords.append((x, y, z)) labels.append(i) print("\n") print(coords) print(labels) print("\n") print("-------------------") i + 1 dir_path = os.path.dirname(os.path.realpath(func_file)) ##Grow ROIs ##If masking, remove those coords that fall outside of the mask if mask != None: from nilearn import masking mask_data, _ = masking._load_mask_img(mask) mask_coords = list(zip(*np.where(mask_data != 0))) for coord in coords: if coord in mask_coords: print('Removing coordinate: ' + str(coord) + ' since it falls outside of network mask...') coords.remove(coord) masker = input_data.NiftiSpheresMasker(seeds=coords, radius=float(node_size), allow_overlap=True, memory_level=5, memory='nilearn_cache', verbose=2) time_series = masker.fit_transform(func_file) for time_serie, label in zip(time_series.T, labels): plt.plot(time_serie, label=label) plt.title(NETWORK + ' Network Time Series') plt.xlabel('Scan Number') plt.ylabel('Normalized Signal') plt.legend() plt.tight_layout() out_path_fig = dir_path + '/' + ID + '_' + NETWORK + '_TS_plot.png' plt.savefig(out_path_fig) plt.close() connectivity_measure = ConnectivityMeasure(kind='correlation') correlation_matrix = connectivity_measure.fit_transform([time_series ])[0] plot_title = NETWORK + ' Network Time Series' plotting.plot_connectome(correlation_matrix, coords, title=plot_title) ##Display connectome with hemispheric projections. title = "Connectivity Projected on the " + NETWORK out_path_fig = dir_path + '/' + ID + '_' + NETWORK + '_connectome_plot.png' plotting.plot_connectome(correlation_matrix, coords, title=title, display_mode='lyrz', output_file=out_path_fig) time_series_path = dir_path + '/' + ID + '_' + NETWORK + '_ts.txt' np.savetxt(time_series_path, time_series, delimiter='\t') mx = genfromtxt(time_series_path, delimiter='') else: DR_st_1 = input_file dir_path = os.path.dirname(os.path.realpath(DR_st_1)) mx = genfromtxt(DR_st_1, delimiter='') from sklearn.covariance import GraphLassoCV, ShrunkCovariance, graph_lasso estimator = GraphLassoCV() try: est = estimator.fit(mx) except: print( "Error: Lasso sparse matrix modeling failed. Check your input time-series data..." ) # emp_cov = covariance.empirical_covariance(mx) # shrunk_cov = covariance.shrunk_covariance(emp_cov, shrinkage=0.8) # Set shrinkage closer to 1 for poorly-conditioned data # # alphaRange = 10.0 ** np.arange(-8,0) # 1e-7 to 1e-1 by order of magnitude # for alpha in alphaRange: # try: # estimator = covariance.graph_lasso(shrunk_cov, alpha) # print("Calculated graph-lasso covariance matrix for alpha=%s"%alpha) # except FloatingPointError: # print("Failed at alpha=%s"%alpha) # estimator = ShrunkCovariance() # est = estimator.fit(mx) if NETWORK != None: est_path = dir_path + '/' + ID + '_' + NETWORK + '_est%s.txt' % ( '_sps_inv' if sps_model else '') else: est_path = dir_path + '/' + ID + '_est%s.txt' % ('_sps_inv' if sps_model else '') if sps_model == False: if NETWORK != None: np.savetxt(est_path, correlation_matrix, delimiter='\t') else: np.savetxt(est_path, correlation_matrix, delimiter='\t') elif sps_model == True: np.savetxt(est_path, estimator.precision_, delimiter='\t') return (mx, est_path)
def run_struct_mapping(FSLDIR, ID, bedpostx_dir, dir_path, NETWORK, coords_MNI, node_size, atlas_select, atlas_name, label_names, plot_switch): edge_threshold = 0.90 connectome_fdt_thresh = 1000 ####Auto-set INPUTS#### nodif_brain_mask_path = bedpostx_dir + '/nodif_brain_mask.nii.gz' merged_th_samples_path = bedpostx_dir + '/merged_th1samples.nii.gz' merged_f_samples_path = bedpostx_dir + '/merged_f1samples.nii.gz' merged_ph_samples_path = bedpostx_dir + '/merged_ph1samples.nii.gz' input_MNI = FSLDIR + '/data/standard/MNI152_T1_2mm_brain.nii.gz' probtrackx_output_dir_path = bedpostx_dir + '/probtrackx_' + NETWORK ####Auto-set INPUTS#### ##Delete any existing roi spheres del_files_spheres = glob.glob(bedpostx_dir + '/roi_sphere*diff.nii.gz') try: for i in del_files_spheres: os.remove(i) except: pass ##Create transform matrix between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = merged_f_samples_path flirt.inputs.in_file = input_MNI flirt.inputs.out_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.run() ##Apply transform between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = merged_f_samples_path flirt.inputs.in_file = input_MNI flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.inputs.out_file = bedpostx_dir + '/xfms/MNI2diff_affine.nii.gz' flirt.run() x_vox = np.diagonal( masking._load_mask_img(nodif_brain_mask_path)[1][:3, 0:3])[0] y_vox = np.diagonal( masking._load_mask_img(nodif_brain_mask_path)[1][:3, 0:3])[1] z_vox = np.diagonal( masking._load_mask_img(nodif_brain_mask_path)[1][:3, 0:3])[2] def mmToVox(mmcoords): voxcoords = ['', '', ''] voxcoords[0] = int((round(int(mmcoords[0]) / x_vox)) + 45) voxcoords[1] = int((round(int(mmcoords[1]) / y_vox)) + 63) voxcoords[2] = int((round(int(mmcoords[2]) / z_vox)) + 36) return voxcoords ##Convert coords back to voxels coords_vox = [] for coord in coords_MNI: coords_vox.append(mmToVox(coord)) coords = list(tuple(x) for x in coords_vox) j = 0 for i in coords: ##Grow spheres at ROI X = coords[j][0] Y = coords[j][1] Z = coords[j][2] out_file1 = bedpostx_dir + '/roi_point_' + str(j) + '.nii.gz' args = '-mul 0 -add 1 -roi ' + str(X) + ' 1 ' + str(Y) + ' 1 ' + str( Z) + ' 1 0 1' maths = fsl.ImageMaths(in_file=input_MNI, op_string=args, out_file=out_file1) os.system(maths.cmdline + ' -odt float') out_file2 = bedpostx_dir + '/roi_sphere_' + str(j) + '.nii.gz' args = '-kernel sphere ' + str(node_size) + ' -fmean -bin' maths = fsl.ImageMaths(in_file=out_file1, op_string=args, out_file=out_file2) os.system(maths.cmdline + ' -odt float') ##Map ROIs from Standard Space to diffusion Space: ##Applying xfm and input matrix to transform ROI's between diff and MNI using FLIRT, flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = nodif_brain_mask_path flirt.inputs.in_file = out_file2 out_file_diff = out_file2.split('.nii')[0] + '_diff.nii.gz' flirt.inputs.out_file = out_file_diff flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/MNI2diff.mat' flirt.run() j = j + 1 if not os.path.exists(probtrackx_output_dir_path): os.makedirs(probtrackx_output_dir_path) seed_files = glob.glob(bedpostx_dir + '/*diff.nii.gz') seeds_text = probtrackx_output_dir_path + '/masks.txt' try: os.remove(seeds_text) except OSError: pass seeds_file_list = [] for seed_file in seed_files: seeds_file_list.append(seed_file) f = open(seeds_text, 'w') l1 = map(lambda x: x + '\n', seeds_file_list) f.writelines(l1) f.close() del_files_points = glob.glob(bedpostx_dir + '/roi_point*.nii.gz') for i in del_files_points: os.remove(i) del_files_spheres = glob.glob(bedpostx_dir + '/roi_sphere*[!diff].nii.gz') for i in del_files_spheres: os.remove(i) mx_path = dir_path + '/' + str(ID) + '_' + NETWORK + '_structural_mx.txt' probtrackx2 = pe.Node(interface=fsl.ProbTrackX2(), name='probtrackx2') probtrackx2.inputs.network = True probtrackx2.inputs.seed = seeds_text probtrackx2.inputs.onewaycondition = True probtrackx2.inputs.c_thresh = 0.2 probtrackx2.inputs.n_steps = 2000 probtrackx2.inputs.step_length = 0.5 probtrackx2.inputs.n_samples = 5000 probtrackx2.inputs.dist_thresh = 0.0 probtrackx2.inputs.opd = True probtrackx2.inputs.loop_check = True probtrackx2.inputs.omatrix1 = True probtrackx2.overwrite = True probtrackx2.inputs.verbose = True probtrackx2.inputs.mask = nodif_brain_mask_path probtrackx2.inputs.out_dir = probtrackx_output_dir_path probtrackx2.inputs.thsamples = merged_th_samples_path probtrackx2.inputs.fsamples = merged_f_samples_path probtrackx2.inputs.phsamples = merged_ph_samples_path probtrackx2.iterables = ("seed", seed_files) try: probtrackx2.inputs.avoid_mp = vetricular_CSF_mask_path except: pass probtrackx2.run() del (probtrackx2) if os.path.exists(probtrackx_output_dir_path + '/fdt_network_matrix'): mx = np.genfromtxt(probtrackx_output_dir_path + '/fdt_network_matrix') waytotal = np.genfromtxt(probtrackx_output_dir_path + '/waytotal') np.seterr(divide='ignore', invalid='ignore') conn_matrix = np.divide(mx, waytotal) conn_matrix[np.isnan(conn_matrix)] = 0 conn_matrix = np.nan_to_num(conn_matrix) conn_matrix = normalize(conn_matrix) ##Save matrix out_path_mx = dir_path + '/' + str( ID) + '_' + NETWORK + '_structural_mx.txt' np.savetxt(out_path_mx, conn_matrix, delimiter='\t') if plot_switch == True: rois_num = conn_matrix.shape[0] print("Creating plot of dimensions:\n" + str(rois_num) + ' x ' + str(rois_num)) plt.figure(figsize=(10, 10)) plt.imshow(conn_matrix, interpolation="nearest", vmax=1, vmin=-1, cmap=plt.cm.RdBu_r) ##And display the labels plt.colorbar() plt.title(atlas_select.upper() + ' ' + NETWORK + ' Structural Connectivity') out_path_fig = dir_path + '/' + str( ID) + '_' + NETWORK + '_structural_adj_mat.png' plt.savefig(out_path_fig) plt.close() conn_matrix_symm = np.maximum(conn_matrix, conn_matrix.transpose()) fdt_paths_loc = probtrackx_output_dir_path + '/fdt_paths.nii.gz' ##Plotting with glass brain ##Create transform matrix between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = input_MNI flirt.inputs.in_file = nodif_brain_mask_path flirt.inputs.out_matrix_file = bedpostx_dir + '/xfms/diff2MNI.mat' flirt.run() ##Apply transform between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = input_MNI flirt.inputs.in_file = nodif_brain_mask_path flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/diff2MNI.mat' flirt.inputs.out_file = bedpostx_dir + '/xfms/diff2MNI_affine.nii.gz' flirt.run() flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = input_MNI flirt.inputs.in_file = fdt_paths_loc out_file_MNI = fdt_paths_loc.split('.nii')[0] + '_MNI.nii.gz' flirt.inputs.out_file = out_file_MNI flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = bedpostx_dir + '/xfms/diff2MNI.mat' flirt.run() fdt_paths_MNI_loc = probtrackx_output_dir_path + '/fdt_paths_MNI.nii.gz' if plot_switch == True: norm = colors.Normalize(vmin=-1, vmax=1) clust_pal = sns.color_palette("Blues_r", 4) clust_colors = colors.to_rgba_array(clust_pal) connectome = plotting.plot_connectome( conn_matrix_symm, coords_MNI, edge_threshold=edge_threshold, node_color=clust_colors, edge_cmap=plotting.cm.black_blue_r) connectome.add_overlay(img=fdt_paths_MNI_loc, threshold=connectome_fdt_thresh, cmap=plotting.cm.cyan_copper_r) out_file_path = dir_path + '/structural_connectome_fig_' + NETWORK + '_' + str( ID) + '.png' plt.savefig(out_file_path) plt.close() from pynets import plotting as pynplot NETWORK = NETWORK + '_structural' pynplot.plot_connectogram(conn_matrix, conn_model, atlas_name, dir_path, ID, NETWORK, label_names) if NETWORK != None: est_path = dir_path + '/' + ID + '_' + NETWORK + '_structural_est.txt' else: est_path = dir_path + '/' + ID + '_structural_est.txt' try: np.savetxt(est_path, conn_matrix_symm, delimiter='\t') except RuntimeError: print('Diffusion network connectome failed!') return (est_path)
def lines(xstart, ystart, xend, yend, color=None, n_segments=100, comet=False, transparent=False, alpha_start=0.01, alpha_end=1, cmap=None, ax=None, vertical=False, reverse_cmap=False, **kwargs): """ Plots lines using matplotlib.collections.LineCollection. This is a fast way to plot multiple lines without loops. Also enables lines that increase in width or opacity by splitting the line into n_segments of increasing width or opacity as the line progresses. Parameters ---------- xstart, ystart, xend, yend: array-like or scalar. Commonly, these parameters are 1D arrays. These should be the start and end coordinates of the lines. color : A matplotlib color or sequence of colors, defaults to None. Defaults to None. In that case the marker color is determined by the value rcParams['lines.color'] n_segments : int, default 100 If comet=True or transparent=True this is used to split the line into n_segments of increasing width/opacity. comet : bool default False Whether to plot the lines increasing in width. transparent : bool, default False Whether to plot the lines increasing in opacity. linewidth or lw : array-like or scalar, default 5. Multiple linewidths not supported for the comet or transparent lines. alpha_start: float, default 0.01 The starting alpha value for transparent lines, between 0 (transparent) and 1 (opaque). If transparent = True the line will be drawn to linearly increase in opacity between alpha_start and alpha_end. alpha_end : float, default 1 The ending alpha value for transparent lines, between 0 (transparent) and 1 (opaque). If transparent = True the line will be drawn to linearly increase in opacity between alpha_start and alpha_end. cmap : str, default None A matplotlib cmap (colormap) name vertical : bool, default False If the orientation is vertical (True), then the code switches the x and y coordinates. reverse_cmap : bool, default False Whether to reverse the cmap colors. If the pitch is horizontal and the y-axis is inverted then set this to True. ax : matplotlib.axes.Axes, default None The axis to plot on. **kwargs : All other keyword arguments are passed on to matplotlib.collections.LineCollection. Returns ------- LineCollection : matplotlib.collections.LineCollection Examples -------- >>> from mplsoccer import Pitch >>> pitch = Pitch() >>> fig, ax = pitch.draw() >>> pitch.lines(20, 20, 45, 80, comet=True, transparent=True, ax=ax) >>> from mplsoccer.linecollection import lines >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> lines([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax) """ validate_ax(ax) if not isinstance(comet, bool): raise TypeError( "Invalid argument: comet should be bool (True or False).") if not isinstance(transparent, bool): raise TypeError( "Invalid argument: transparent should be bool (True or False).") if alpha_start < 0 or alpha_start > 1: raise TypeError("alpha_start values should be within 0-1 range") if alpha_end < 0 or alpha_end > 1: raise TypeError("alpha_end values should be within 0-1 range") if alpha_start > alpha_end: msg = "Alpha start > alpha end. The line will increase in transparency nearer to the end" warnings.warn(msg) if 'colors' in kwargs.keys(): warnings.warn( "lines method takes 'color' as an argument, 'colors' in ignored") if color is not None and cmap is not None: raise ValueError("Only use one of color or cmap arguments not both.") if 'lw' in kwargs.keys() and 'linewidth' in kwargs.keys(): raise TypeError( "lines got multiple values for 'linewidth' argument (linewidth and lw)." ) # set linewidth if 'lw' in kwargs.keys(): lw = kwargs.pop('lw', 5) elif 'linewidth' in kwargs.keys(): lw = kwargs.pop('linewidth', 5) else: lw = 5 # to arrays xstart = np.ravel(xstart) ystart = np.ravel(ystart) xend = np.ravel(xend) yend = np.ravel(yend) lw = np.ravel(lw) if (comet or transparent) and (lw.size > 1): msg = "Multiple linewidths with a comet or transparent line is not implemented." raise NotImplementedError(msg) # set color if color is None and cmap is None: color = rcParams['lines.color'] if (comet or transparent) and (cmap is None) and ( to_rgba_array(color).shape[0] > 1): msg = "Multiple colors with a comet or transparent line is not implemented." raise NotImplementedError(msg) if xstart.size != ystart.size: raise ValueError("xstart and ystart must be the same size") if xstart.size != xend.size: raise ValueError("xstart and xend must be the same size") if ystart.size != yend.size: raise ValueError("ystart and yend must be the same size") if (lw.size > 1) and (lw.size != xstart.size): raise ValueError("lw and xstart must be the same size") if lw.size == 1: lw = lw[0] if vertical: ystart, xstart = xstart, ystart yend, xend = xend, yend # create linewidth if comet: lw = np.linspace(1, lw, n_segments) handler_first_lw = False else: handler_first_lw = True if (transparent is False) and (comet is False) and (cmap is None): multi_segment = False else: multi_segment = True if transparent: cmap = create_transparent_cmap(color, cmap, n_segments, alpha_start, alpha_end) if isinstance(cmap, str): cmap = get_cmap(cmap) if cmap is not None: handler_cmap = True line_collection = _lines_cmap(xstart, ystart, xend, yend, lw=lw, cmap=cmap, ax=ax, n_segments=n_segments, multi_segment=multi_segment, reverse_cmap=reverse_cmap, **kwargs) else: handler_cmap = False line_collection = _lines_no_cmap(xstart, ystart, xend, yend, lw=lw, color=color, ax=ax, n_segments=n_segments, multi_segment=multi_segment, **kwargs) line_collection_handler = HandlerLines(numpoints=n_segments, invert_y=reverse_cmap, first_lw=handler_first_lw, use_cmap=handler_cmap) Legend.update_default_handler_map( {line_collection: line_collection_handler}) return line_collection
def plot_khat( hover_label, hover_format, ax, figsize, xdata, khats, kwargs, threshold, coord_labels, show_hlines, show_bins, hlines_kwargs, xlabels, legend, color, dims, textsize, markersize, n_data_points, bin_format, backend_kwargs, show, ): """Matplotlib khat plot.""" if hover_label and mpl.get_backend() not in mpl.rcsetup.interactive_bk: hover_label = False warnings.warn( "hover labels are only available with interactive backends. To switch to an " "interactive backend from ipython or jupyter, use `%matplotlib` there should be " "no need to restart the kernel. For other cases, see " "https://matplotlib.org/3.1.0/tutorials/introductory/usage.html#backends", UserWarning, ) if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwargs, } (figsize, ax_labelsize, _, xt_labelsize, linewidth, scaled_markersize) = _scale_fig_size(figsize, textsize) backend_kwargs.setdefault("figsize", figsize) backend_kwargs["squeeze"] = True hlines_kwargs = matplotlib_kwarg_dealiaser(hlines_kwargs, "hlines") hlines_kwargs.setdefault("hlines", [0, 0.5, 0.7, 1]) hlines_kwargs.setdefault("linestyle", [":", "-.", "--", "-"]) hlines_kwargs.setdefault("alpha", 0.7) hlines_kwargs.setdefault("zorder", -1) hlines_kwargs.setdefault("color", "C1") hlines_kwargs["color"] = vectorized_to_hex(hlines_kwargs["color"]) if markersize is None: markersize = scaled_markersize**2 # s in scatter plot mus be markersize square # for dots to have the same size kwargs = matplotlib_kwarg_dealiaser(kwargs, "scatter") kwargs.setdefault("s", markersize) kwargs.setdefault("marker", "+") c_kwarg = kwargs.get("c", None) if c_kwarg is None: color_mapping = None cmap = None if isinstance(color, str): if color in dims: colors, color_mapping = color_from_dim(khats, color) cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) rgba_c = cmap(colors) else: legend = False rgba_c = to_rgba_array(np.full(n_data_points, color)) else: legend = False try: rgba_c = to_rgba_array(color) except ValueError: cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) norm_fun = kwargs.get( "norm", mpl.colors.Normalize(color.min(), color.max())) rgba_c = cmap(norm_fun(color)) khats = khats if isinstance(khats, np.ndarray) else khats.values.flatten() alphas = 0.5 + 0.2 * (khats > 0.5) + 0.3 * (khats > 1) rgba_c[:, 3] = alphas rgba_c = vectorized_to_hex(rgba_c) kwargs["c"] = rgba_c else: if isinstance(c_kwarg, str): if c_kwarg in dims: colors, color_mapping = color_from_dim(khats, c_kwarg) else: legend = False else: legend = False if ax is None: fig, ax = create_axes_grid( 1, backend_kwargs=backend_kwargs, ) else: fig = ax.get_figure() sc_plot = ax.scatter(xdata, khats, **kwargs) if threshold is not None: idxs = xdata[khats > threshold] for idx in idxs: ax.text( idx, khats[idx], coord_labels[idx], horizontalalignment="center", verticalalignment="bottom", fontsize=0.8 * xt_labelsize, ) xmin, xmax = ax.get_xlim() if show_bins: xmax += n_data_points / 12 ylims1 = ax.get_ylim() ylims2 = ax.get_ylim() ymin = min(ylims1[0], ylims2[0]) ymax = min(ylims1[1], ylims2[1]) if show_hlines: ax.hlines(hlines_kwargs.pop("hlines"), xmin=xmin, xmax=xmax, linewidth=linewidth, **hlines_kwargs) if show_bins: bin_edges = np.array([ymin, 0.5, 0.7, 1, ymax]) bin_edges = bin_edges[(bin_edges >= ymin) & (bin_edges <= ymax)] hist, _, _ = histogram(khats, bin_edges) for idx, count in enumerate(hist): ax.text( (n_data_points - 1 + xmax) / 2, np.mean(bin_edges[idx:idx + 2]), bin_format.format(count, count / n_data_points * 100), horizontalalignment="center", verticalalignment="center", ) ax.set_xlabel("Data Point", fontsize=ax_labelsize) ax.set_ylabel(r"Shape parameter k", fontsize=ax_labelsize) ax.tick_params(labelsize=xt_labelsize) if xlabels: set_xticklabels(ax, coord_labels) fig.autofmt_xdate() fig.tight_layout() if legend: kwargs.pop("c") ncols = len(color_mapping) // 6 + 1 for label, float_color in color_mapping.items(): ax.scatter([], [], c=[cmap(float_color)], label=label, **kwargs) ax.legend(ncol=ncols, title=color) if hover_label and mpl.get_backend() in mpl.rcsetup.interactive_bk: _make_hover_annotation(fig, ax, sc_plot, coord_labels, rgba_c, hover_format) if backend_show(show): plt.show() return ax
def as_vtk_cmap(cmap, cache=True): """Colormaps are generally converted implicitly from any valid format to a ``vtk.vtkLookupTable`` using this method. `Any valid format` is defined as the following: #. A string matplotlib colormap name such as ``'RdYlGn'``. #. Anything out of the ``matplotlib.cm`` package. #. A list of named colors such as ``["red", "white", "blue"]``. See :meth:`cmap_from_list` for more details and flexibility. #. An ``(n, 3)`` or ``(n, 4)`` numpy array of RGB(A) int or float values. #. A callable that takes an array of scalars and returns an array of form **4**. Unless specified otherwise using ``cache=False``, named colormaps of form **1** are cached in ``vtkplotlib.colors.converted_cmaps``. If you intend to modify the vtkLookupTable then it's best not to allow caching. .. note:: VTK doesn't interpolate between colors. i.e if you use form **4** and only provide a short list of colors then the resulting heatmap will be block colors rather than a smooth gradient. .. note:: Whilst VTK appears to support opacity gradients in the colormaps, it doesn't actually use them. If your colormap says opacity should vary with scalars then the opacity is averaged for the plot. """ if isinstance(cmap, _future_utils.string_types): if cache and cmap in converted_cmaps: return converted_cmaps[cmap] cmap = cm.get_cmap(cmap) if isinstance(cmap, vtk.vtkLookupTable): return cmap if cache and isinstance( cmap, (colors.ListedColormap, colors.LinearSegmentedColormap)): name = cmap.name if name in converted_cmaps: return converted_cmaps[name] else: name = None if isinstance(cmap, colors.ListedColormap): cmap = np.array(cmap.colors) if callable(cmap): cmap = cmap(np.arange(256, dtype=np.uint8)) if isinstance(cmap, list): cmap = cmap_from_list(cmap) if not isinstance(cmap, np.ndarray): raise TypeError("cmap is of an invalid type {}.".format(type(cmap))) if cmap.ndim == 2 and 3 <= cmap.shape[1] <= 4: cmap = np.ascontiguousarray( (colors.to_rgba_array(cmap) * 255).astype(np.uint8)) table = vtk.vtkLookupTable() table.SetTable(numpy_to_vtk(cmap)) table._numpy_ref = cmap _temp.append(cmap) if name is not None: converted_cmaps[name] = table return table else: raise ValueError( "`cmap` should have shape (n, 3) or (n, 4). Received {}.".format( cmap.shape))
def structural_plotting(conn_matrix_symm, label_names, atlas_select, ID, bedpostx_dir, network, parc, mask, coords, dir_path, conn_model, thr, node_size, smooth): import matplotlib matplotlib.use('agg') from matplotlib import pyplot as plt import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe import seaborn as sns import pkg_resources from matplotlib import colors from nilearn import plotting as niplot from pynets import plotting try: import cPickle as pickle except ImportError: import _pickle as pickle edge_threshold = 0.10 connectome_fdt_thresh = 90 dpi_resolution = 500 bpx_trx = False # # Auto-set INPUTS# # try: FSLDIR = os.environ['FSLDIR'] except NameError: print('FSLDIR environment variable not set!') nodif_brain_mask_path = "%s%s" % (bedpostx_dir, '/nodif_brain_mask.nii.gz') if parc is True: node_size = 'parc' if network: probtrackx_output_dir_path = "%s%s%s%s%s%s" % ( dir_path, '/probtrackx_', str(node_size), '%s' % ("mm_" if node_size != 'parc' else "_"), "%s" % ("%s%s" % (smooth, 'fwhm_') if float(smooth) > 0 else 'nosm_'), network) else: probtrackx_output_dir_path = "%s%s%s%s%s" % ( dir_path, '/probtrackx_WB_', str(node_size), '%s' % ("mm_" if node_size != 'parc' else "_"), "%s" % ("%s%s" % (smooth, 'fwhm') if float(smooth) > 0 else 'nosm')) # # Auto-set INPUTS# # # G_pre=nx.from_numpy_matrix(conn_matrix_symm) # if pruning is True: # [G, pruned_nodes] = most_important(G_pre) # else: # G = G_pre # conn_matrix = nx.to_numpy_array(G) # # pruned_nodes.sort(reverse=True) # for j in pruned_nodes: # del label_names[label_names.index(label_names[j])] # del coords[coords.index(coords[j])] # # pruned_edges.sort(reverse=True) # for j in pruned_edges: # del label_names[label_names.index(label_names[j])] # del coords[coords.index(coords[j])] # Plot adj. matrix based on determined inputs plotting.plot_conn_mat_struct(conn_matrix_symm, conn_model, atlas_select, dir_path, ID, network, label_names, mask, thr, node_size, smooth) if bpx_trx is True: # Prepare glass brain figure fdt_paths_loc = "%s%s" % (probtrackx_output_dir_path, '/fdt_paths.nii.gz') # Create transform matrix between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = "%s%s" % ( FSLDIR, '/data/standard/MNI152_T1_1mm_brain.nii.gz') flirt.inputs.in_file = nodif_brain_mask_path flirt.inputs.out_matrix_file = "%s%s" % (bedpostx_dir, '/xfms/diff2MNI.mat') flirt.inputs.out_file = '/tmp/out_flirt.nii.gz' flirt.run() # Apply transform between diff and MNI using FLIRT flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = "%s%s" % ( FSLDIR, '/data/standard/MNI152_T1_1mm_brain.nii.gz') flirt.inputs.in_file = nodif_brain_mask_path flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = "%s%s" % (bedpostx_dir, '/xfms/diff2MNI.mat') flirt.inputs.out_file = "%s%s" % (bedpostx_dir, '/xfms/diff2MNI_affine.nii.gz') flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.run() flirt = pe.Node(interface=fsl.FLIRT(cost_func='mutualinfo'), name='coregister') flirt.inputs.reference = "%s%s" % ( FSLDIR, '/data/standard/MNI152_T1_1mm_brain.nii.gz') flirt.inputs.in_file = fdt_paths_loc out_file_MNI = "%s%s" % (fdt_paths_loc.split('.nii')[0], '_MNI.nii.gz') flirt.inputs.out_file = out_file_MNI flirt.inputs.out_matrix_file = '/tmp/out_flirt.mat' flirt.inputs.apply_xfm = True flirt.inputs.in_matrix_file = "%s%s" % (bedpostx_dir, '/xfms/diff2MNI.mat') flirt.run() fdt_paths_MNI_loc = "%s%s" % (probtrackx_output_dir_path, '/fdt_paths_MNI.nii.gz') else: fdt_paths_MNI_loc = None colors.Normalize(vmin=-1, vmax=1) clust_pal = sns.color_palette("Blues_r", 4) clust_colors = colors.to_rgba_array(clust_pal) # Plotting with glass brain ch2better_loc = pkg_resources.resource_filename( "pynets", "templates/ch2better.nii.gz") connectome = niplot.plot_connectome(np.zeros(shape=(1, 1)), [(0, 0, 0)], node_size=0.0001, black_bg=True) connectome.add_overlay(ch2better_loc, alpha=0.5, cmap=plt.cm.gray) [z_min, z_max] = -np.abs(conn_matrix_symm).max(), np.abs(conn_matrix_symm).max() connectome.add_graph(conn_matrix_symm, coords, edge_threshold=edge_threshold, node_color=clust_colors, edge_cmap=plt.cm.binary, edge_vmax=z_max, edge_vmin=z_min, node_size=4) if bpx_trx is True and fdt_paths_MNI_loc: connectome.add_overlay(img=fdt_paths_MNI_loc, threshold=connectome_fdt_thresh, cmap=niplot.cm.cyan_copper_r, alpha=0.6) # Plot connectome if mask: out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % ( dir_path, '/', ID, '_', str(atlas_select), '_', str(conn_model), '_', str(os.path.basename(mask).split('.')[0]), "%s" % ("%s%s%s" % ('_', network, '_') if network else "_"), str(thr), '_', str(node_size), '%s' % ("mm_" if node_size != 'parc' else "_"), "%s" % ("%s%s" % (smooth, 'fwhm_') if float(smooth) > 0 else 'nosm_'), 'struct_glass_viz.png') coord_path = "%s%s%s%s" % (dir_path, '/struct_coords_', os.path.basename(mask).split('.')[0], '_plotting.pkl') labels_path = "%s%s%s%s" % (dir_path, '/struct_labelnames_', os.path.basename(mask).split('.')[0], '_plotting.pkl') else: out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % ( dir_path, '/', ID, '_', str(atlas_select), '_', str(conn_model), "%s" % ("%s%s%s" % ('_', network, '_') if network else "_"), str(thr), '_', str(node_size), '%s' % ("mm_" if node_size != 'parc' else "_"), "%s" % ("%s%s" % (smooth, 'fwhm_') if float(smooth) > 0 else 'nosm_'), 'struct_glass_viz.png') coord_path = "%s%s" % (dir_path, '/struct_coords_plotting.pkl') labels_path = "%s%s" % (dir_path, '/struct_labelnames_plotting.pkl') # Save coords to pickle with open(coord_path, 'wb') as f: pickle.dump(coords, f, protocol=2) # Save labels to pickle with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) connectome.savefig(out_path_fig, dpi=dpi_resolution) # connectome.savefig(out_path_fig, dpi=dpi_resolution, facecolor ='k', edgecolor ='k') connectome.close() return
def test_cmap_and_norm_from_levels_and_colors2(): levels = [-1, 2, 2.5, 3] colors = ['red', (0, 1, 0), 'blue', (0.5, 0.5, 0.5), (0.0, 0.0, 0.0, 1.0)] clr = mcolors.to_rgba_array(colors) bad = (0.1, 0.1, 0.1, 0.1) no_color = (0.0, 0.0, 0.0, 0.0) masked_value = 'masked_value' # Define the test values which are of interest. # Note: levels are lev[i] <= v < lev[i+1] tests = [ ('both', None, { -2: clr[0], -1: clr[1], 2: clr[2], 2.25: clr[2], 3: clr[4], 3.5: clr[4], masked_value: bad }), ('min', -1, { -2: clr[0], -1: clr[1], 2: clr[2], 2.25: clr[2], 3: no_color, 3.5: no_color, masked_value: bad }), ('max', -1, { -2: no_color, -1: clr[0], 2: clr[1], 2.25: clr[1], 3: clr[3], 3.5: clr[3], masked_value: bad }), ('neither', -2, { -2: no_color, -1: clr[0], 2: clr[1], 2.25: clr[1], 3: no_color, 3.5: no_color, masked_value: bad }), ] for extend, i1, cases in tests: cmap, norm = mcolors.from_levels_and_colors(levels, colors[0:i1], extend=extend) cmap.set_bad(bad) for d_val, expected_color in cases.items(): if d_val == masked_value: d_val = np.ma.array([1], mask=True) else: d_val = [d_val] assert_array_equal( expected_color, cmap(norm(d_val))[0], 'Wih extend={0!r} and data ' 'value={1!r}'.format(extend, d_val)) assert_raises(ValueError, mcolors.from_levels_and_colors, levels, colors)
def plot_surf4( meshes, overlays=None, sulc_maps=None, ctx_masks=None, labels=None, label_colors=None, label_alpha=0.5, cmap=None, shuffle_cmap=False, threshold=None, vmin=None, vmax=None, avg_method="mean", colorbar=False, output_file="plot.png", title="", ): """Plottig of surface mesh with optional overlay data and sulcal maps. Parameters ---------- meshes: list of two files [left hemi (lh), right hemi (rh)] Surface mesh geometry, Valid file formats are .gii or Freesurfer specific files such as .orig, .pial, .sphere, .white, .inflated overlays: optional, list of two files [lh, rh] Data to be displayed on the surface mesh. Valid formats are .gii, or Freesurfer specific files such as .thickness, .curv, .sulc, .annot, .label sulc_maps: optional, list of two files [lh, rh] Sulcal depth (or curvature) map to be plotted on the mesh in greyscale, underneath the overlay. Valid formats are .gii, or Freesurfer specific files .sulc and .curv ctx_masks: optional, list of two files [lh, rh] Cortical labels (masks) to restrict overlay data. Valid formats are Freesurfer specific file .label, or .gii labels: list of lists of the form [ [lh_label1, rh_label1], [lh_label2, rh_label2], ... ] Labels to be displayed on the surface mesh. Valid formats Freesurfer specific files (.label) or equivalent files in .gii format label_colors: list of matplotlib colors to be assigned to labels, of the form [ color_label1, color_label2, ... ] Must have the same langth as the list of labels. label_alpha: float, transparency level for label colors fro 0 (translucent) to 1 (fully opaque) cmap: matplotlib colormap, str or colormap object, default is None To use for plotting of the overlay. Either a string which is a name of a matplotlib colormap, or a matplotlib colormap object. If None, matplotlib default will be chosen. shuffle_cmap: boolean If True, randomly shuffle the cmap (useful for parcellations) avg_method: {'mean', 'median'}, default is 'mean' How to average vertex values to derive the face value, mean results in smooth, median in sharp boundaries (e.g. for parcellations). colorbar : bool, optional, default is False If True, a colorbar of surf_map is displayed. threshold : a number or None, default is None. If None is given, the image is not thresholded. If a number is given, it is used to threshold the image, values below the threshold (in absolute value) are plotted as transparent. vmin, vmax: lower / upper bound to plot surf_data values If None , the values will be set to min/max of the data title : str, optional Figure title. output_file: str, or None, optional The name of an image file to export plot to. Valid extensions are .png, .pdf, .svg. If output_file is not None, the plot is saved to a file, and the display is closed. """ print("plotting...") # if no cmap is given, set to matplotlib default if cmap is None: cmap = plt.cm.get_cmap(plt.rcParamsDefault["image.cmap"]) else: # if cmap is given as string, translate to matplotlib cmap if isinstance(cmap, str): cmap = plt.cm.get_cmap(cmap) # randomly shuffle colormap if prompted if shuffle_cmap: vals = np.linspace(0, 1, 256) np.random.shuffle(vals) cmap = ListedColormap(plt.cm.get_cmap(cmap)(vals)) # initiate figure fig = plt.figure(figsize=(8, 6)) # select which views to show # [lh_lateral, lh medial], [rh_lateral, rh_medial] rotations_both = [[90, 270], [270, 90]] for m, mesh in enumerate(meshes): # load mesh vertices, faces = surface.load_surf_mesh(mesh) vertices = vertices.astype(np.float) faces = faces.astype(int) # Set up lighting, intensity and shading rotations = rotations_both[m] vert_range = max(vertices.max(0) - vertices.min(0)) vertices = (vertices - (vertices.max(0) + vertices.min(0)) / 2) / vert_range face_normals = normal_vectors(vertices, faces) light = np.array([0, 0, 1]) intensity = np.dot(face_normals, light) shading = 0.7 # shading 0-1. 0=none. 1=full # top 20% all become fully colored denom = np.percentile(intensity, 80) - np.min(intensity) intensity = (1 - shading) + shading * (intensity - np.min(intensity)) / denom intensity[intensity > 1] = 1 # initiate array for face colors face_colors = np.ones((faces.shape[0], 4)) ################################## # read cortex label if provided if ctx_masks is None: mask = np.zeros(vertices.shape[0]).astype(bool) else: mask = np.zeros(vertices.shape[0]).astype(bool) cortex = surface.load_surf_data(ctx_masks[m]) mask[cortex] = 1 # cortical vertices = 1 ################################## # read sulcal map if provided if sulc_maps is None: sulc = np.ones(vertices.shape[0]) * 0.5 else: sulc = surface.load_surf_data(sulc_maps[m]) if sulc.shape[0] != vertices.shape[0]: raise ValueError( "The sulcal map does not have the same " "number of vertices as the mesh." ) sulc_faces = np.mean(sulc[faces], axis=1) # binarize sulcal map if sulc_faces.min() != sulc_faces.max(): neg_sulc = np.where(sulc_faces <= 0) pos_sulc = np.where(sulc_faces > 0) sulc_faces[neg_sulc] = 0 sulc_faces[pos_sulc] = 1 ################################## # read labels if provided label_masks = [] if labels is not None: if len(label_colors) != len(labels): raise ValueError( "labels and label_colors must be" " lists of the same length." ) label_colors = [to_rgba_array(c) for c in label_colors] for c in label_colors: c[0, 3] = label_alpha for label in labels: L_mask = np.zeros(vertices.shape[0]).astype(bool) L_indices = surface.load_surf_data(label[m]) L_mask[L_indices] = 1 # label vertices = 1 label_masks.append(L_mask) label_mask_faces = [np.median(L[faces], axis=1) for L in label_masks] ################################## # read overlay map if provided if overlays is not None: overlay = surface.load_surf_data(overlays[m]) if len(overlay.shape) is not 1: raise ValueError( "overlay can only have one dimension" " but has %i dimensions" % len(overlay.shape) ) if overlay.shape[0] != vertices.shape[0]: raise ValueError( "The overlay does not have the same number" " of vertices as the mesh." ) ################################## # assign greyscale colormap to sulcal map faces greys = plt.get_cmap("Greys", 512) greys_narrow = ListedColormap(greys(np.linspace(0.42, 0.58, 256))) face_colors = greys_narrow(sulc_faces) # Get indices of faces within the cortex if ctx_masks is None: kept_indices = np.arange(sulc_faces.shape[0]) else: mask_faces = np.median(mask[faces], axis=1) kept_indices = np.where(mask_faces >= 0.5)[0] masked_indices = np.where(mask_faces < 0.5)[0] if overlays is not None: # create face values from vertex values by selected avg methods if avg_method == "mean": overlay_faces = np.mean(overlay[faces], axis=1) elif avg_method == "median": overlay_faces = np.median(overlay[faces], axis=1) # if no vmin/vmax are passed figure them out from the data if vmin is None: vmin = np.nanmin(overlay_faces) if vmax is None: vmax = np.nanmax(overlay_faces) # threshold if indicated if threshold is not None: valid_indices = np.where(np.abs(overlay_faces) >= threshold)[0] kept_indices = [i for i in kept_indices if i in valid_indices] # assign colormap to overlay overlay_faces = overlay_faces - vmin overlay_faces = overlay_faces / (vmax - vmin) face_colors[kept_indices] = cmap(overlay_faces[kept_indices]) # make non-cortical faces light grey if ctx_masks is not None: face_colors[masked_indices] = [0.85, 0.85, 0.85, 1] # assign label faces to appropriate color for i, L in enumerate(label_mask_faces): L_idx = np.where(L >= 0.5) # blend (multiply) label color with underlying color face_colors[L_idx] = face_colors[L_idx] * label_colors[i] face_colors[:, 0] *= intensity face_colors[:, 1] *= intensity face_colors[:, 2] *= intensity ################################## # Draw the plot for i, view in enumerate(rotations): MVP = ( perspective(25, 1, 1, 100) @ translate(0, 0, -3) @ yrotate(view) @ xrotate(270) ) # translate coordinates based on viewing position V = np.c_[vertices, np.ones(len(vertices))] @ MVP.T V /= V[:, 3].reshape(-1, 1) V = V[faces] # triangle coordinates T = V[:, :, :2] # get Z values for ordering triangle plotting Z = -V[:, :, 2].mean(axis=1) # sort the triangles based on their z coordinate Zorder = np.argsort(Z) T, C = T[Zorder, :], face_colors[Zorder, :] # add subplot and plot PolyCollection ax = fig.add_subplot( 2, 2, m + 2 * i + 1, xlim=[-1, +1], ylim=[-0.6, +0.6], frameon=False, aspect=1, xticks=[], yticks=[], ) collection = PolyCollection( T, closed=True, antialiased=False, facecolor=C, edgecolor=C, linewidth=0 ) collection.set_alpha(1) ax.add_collection(collection) ################################## # Draw colorbar if prompted if colorbar: our_cmap = plt.get_cmap(cmap) norm = Normalize(vmin=vmin, vmax=vmax) bounds = np.linspace(vmin, vmax, our_cmap.N) if threshold is None: ticks = [vmin, vmax] elif threshold == vmin: ticks = [vmin, vmax] else: if vmin >= 0: ticks = [vmin, threshold, vmax] else: ticks = [vmin, -threshold, threshold, vmax] cmaplist = [our_cmap(i) for i in range(our_cmap.N)] # set colors to grey for absolute values < threshold istart = int(norm(-threshold, clip=True) * (our_cmap.N - 1)) istop = int(norm(threshold, clip=True) * (our_cmap.N - 1)) for i in range(istart, istop): cmaplist[i] = (0.5, 0.5, 0.5, 1.0) our_cmap = LinearSegmentedColormap.from_list( "Custom cmap", cmaplist, our_cmap.N ) # we need to create a proxy mappable proxy_mappable = ScalarMappable(cmap=our_cmap, norm=norm) proxy_mappable.set_array(overlay_faces) cax = plt.axes([0.38, 0.466, 0.24, 0.024]) plt.colorbar( proxy_mappable, cax=cax, boundaries=bounds, ticks=ticks, orientation="horizontal", ) # add annotations if title is not None: fig.text(0.5, 0.51, title, ha="center", va="bottom", fontsize="large") fig.text(0.25, 0.975, "Left", ha="center", va="top") fig.text(0.75, 0.975, "Right", ha="center", va="top") fig.text(0.025, 0.75, "Lateral", ha="left", va="center", rotation=90) fig.text(0.025, 0.25, "Medial", ha="left", va="center", rotation=90) fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) # save file fig.savefig(output_file, dpi=128)
'Factor de raza: asiático', 'Factor de raza: nativo americano' ]) import matplotlib.colors as col import matplotlib.pyplot as plt from matplotlib import figure from matplotlib.backends import backend_agg fig = figure.Figure(figsize=(10, 6)) canvas = backend_agg.FigureCanvasAgg(fig) colors = plt.cm.Spectral(np.linspace(0,1,len(means))) #Modelo 1,2 #colors[2] = col.to_rgba_array('grey') #Modelo 3,4 colors[3] = col.to_rgba_array('blue') #colors[5], colors[6], colors[7] = col.to_rgba_array('grey'), col.to_rgba_array('black'), col.to_rgba_array('pink') ax = fig.add_subplot(1, 1, 1) ax.set_prop_cycle('color', colors) #ax.set_prop_cycle(color = ['black', 'red', 'blue']) #ax.plot(np.linspace(-7, 7, 100), np.ones(100),lw=1, color="black") for i in range(len(means)): if i == len(means) - 1: ax.plot(points[:, i], pdfs[i], lw=2, label = labels[i]) break ax.plot(points[:, i], pdfs[i], lw=2, label = labels[i]) """ for i in range(len(means1)):
def _i_mtv(self, data, wcs, title, isMask): """Internal routine to display an Image or Mask on a DS9 display""" title = str(title) if title else "" dataArr = data.getArray() if isMask: maskPlanes = data.getMaskPlaneDict() nMaskPlanes = max(maskPlanes.values()) + 1 planes = {} # build inverse dictionary for key in maskPlanes: planes[maskPlanes[key]] = key planeList = range(nMaskPlanes) maskArr = np.zeros_like(dataArr, dtype=np.int32) colorNames = ['black'] colorGenerator = self.display.maskColorGenerator(omitBW=True) for p in planeList: color = self.display.getMaskPlaneColor( planes[p]) if p in planes else None if not color: # none was specified color = next(colorGenerator) elif color.lower() == afwDisplay.IGNORE: color = 'black' # we'll set alpha = 0 anyway colorNames.append(color) # # Convert those colours to RGBA so we can have per-mask-plane transparency # and build a colour map # # Pixels equal to 0 don't get set (as no bits are set), so leave them transparent # and start our colours at [1] -- hence "i + 1" below # colors = mpColors.to_rgba_array(colorNames) alphaChannel = 3 # the alpha channel; the A in RGBA colors[0][alphaChannel] = 0.0 # it's black anyway for i, p in enumerate(planeList): if colorNames[i + 1] == 'black': alpha = 0.0 else: alpha = 1 - self._getMaskTransparency(planes[p] if p in planes else None) colors[i + 1][alphaChannel] = alpha cmap = mpColors.ListedColormap(colors) norm = mpColors.NoNorm() else: cmap = self._image_colormap norm = self._normalize ax = self._figure.gca() bbox = data.getBBox() extent = (bbox.getBeginX() - 0.5, bbox.getEndX() - 0.5, bbox.getBeginY() - 0.5, bbox.getEndY() - 0.5) with pyplot.rc_context(dict(interactive=False)): if isMask: for i, p in reversed(list(enumerate(planeList))): if colors[i + 1][alphaChannel] == 0: # colors[0] is reserved continue bitIsSet = (dataArr & (1 << p)) != 0 if bitIsSet.sum() == 0: continue maskArr[ bitIsSet] = i + 1 # + 1 as we set colorNames[0] to black if not self._fastMaskDisplay: # we draw each bitplane separately ax.imshow(maskArr, origin='lower', interpolation='nearest', extent=extent, cmap=cmap, norm=norm) maskArr[:] = 0 if self._fastMaskDisplay: # we only draw the lowest bitplane ax.imshow(maskArr, origin='lower', interpolation='nearest', extent=extent, cmap=cmap, norm=norm) else: mappable = ax.imshow(dataArr, origin='lower', interpolation='nearest', extent=extent, cmap=cmap, norm=norm) self._mappable = mappable self._figure.canvas.draw_idle()
def get_colors(c, num): """Stretch the color argument to provide the required number *num*.""" return np.broadcast_to( mcolors.to_rgba_array(c) if len(c) else [0, 0, 0, 0], (num, 4))
import matplotlib.colors as colors import matplotlib.cm as cm print(colors.to_hex("r")) print(colors.to_rgba_array("r")) print(colors.to_rgba("r")) print(colors.to_rgba([1, 1, 1])) print(cm.get_cmap("Blues").N) print(cm.get_cmap("Blues")(0)) print(cm.get_cmap("Blues")(10)) # print(dir(cm.get_cmap("Blues")# <matplotlib.colors.LinearSegmentedColormap object at 0x7fa6149b5da0>
def plot_khat(khats, color=None, xlabels=False, show_bins=False, bin_format="{1:.1f}%", annotate=False, hover_label=False, hover_format="{1}", figsize=None, textsize=None, coords=None, legend=False, markersize=None, ax=None, hlines_kwargs=None, backend=None, backend_kwargs=None, show=None, **kwargs): """ Plot Pareto tail indices. Parameters ---------- khats : ELPDData cointaining pareto shapes information or array Pareto tail indices. color : str or array_like, optional Colors of the scatter plot, if color is a str all dots will have the same color, if it is the size of the observations, each dot will have the specified color, otherwise, it will be interpreted as a list of the dims to be used for the color code xlabels : bool, optional Use coords as xticklabels show_bins : bool, optional Show the number of khats which fall in each bin. bin_format : str, optional The string is used as formatting guide calling ``bin_format.format(count, pct)``. annotate : bool, optional Show the labels of k values larger than 1. hover_label : bool, optional Show the datapoint label when hovering over it with the mouse. Requires an interactive backend. hover_format : str, optional String used to format the hover label via ``hover_format.format(idx, coord_label)`` figsize : tuple, optional Figure size. If None it will be defined automatically. textsize: float, optional Text size scaling factor for labels, titles and lines. If None it will be autoscaled based on figsize. coords : mapping, optional Coordinates of points to plot. **All** values are used for computation, but only a a subset can be plotted for convenience. legend : bool, optional Include a legend to the plot. Only taken into account when color argument is a dim name. markersize: int, optional markersize for scatter plot. Defaults to `None` in which case it will be chosen based on autoscaling for figsize. ax: axes, optional Matplotlib axes or bokeh figures. hlines_kwargs: dictionary, optional Additional keywords passed to ax.hlines. backend: str, optional Select plotting backend {"matplotlib","bokeh"}. Default "matplotlib". backend_kwargs: bool, optional These are kwargs specific to the backend being used. For additional documentation check the plotting method of the backend. show : bool, optional Call backend show function. kwargs : Additional keywords passed to ax.scatter. Returns ------- axes : matplotlib axes or bokeh figures Examples -------- Plot estimated pareto shape parameters showing how many fall in each category. .. plot:: :context: close-figs >>> import arviz as az >>> radon = az.load_arviz_data("radon") >>> loo_radon = az.loo(radon, pointwise=True) >>> az.plot_khat(loo_radon, show_bins=True) Show xlabels .. plot:: :context: close-figs >>> centered_eight = az.load_arviz_data("centered_eight") >>> khats = az.loo(centered_eight, pointwise=True).pareto_k >>> az.plot_khat(khats, xlabels=True, annotate=True) Use custom color scheme .. plot:: :context: close-figs >>> counties = radon.posterior.County[radon.constant_data.county_idx].values >>> colors = [ ... "blue" if county[-1] in ("A", "N") else "green" for county in counties ... ] >>> az.plot_khat(loo_radon, color=colors) """ hlines_kwargs = matplotlib_kwarg_dealiaser(hlines_kwargs, "hlines") hlines_kwargs.setdefault("linestyle", [":", "-.", "--", "-"]) hlines_kwargs.setdefault("alpha", 0.7) hlines_kwargs.setdefault("zorder", -1) hlines_kwargs.setdefault("color", "C1") hlines_kwargs["color"] = vectorized_to_hex(hlines_kwargs["color"]) if coords is None: coords = {} if color is None: color = "C0" if isinstance(khats, np.ndarray): khats = khats.flatten() xlabels = False legend = False dims = [] else: if isinstance(khats, ELPDData): khats = khats.pareto_k if not isinstance(khats, DataArray): raise ValueError( "Incorrect khat data input. Check the documentation") khats = get_coords(khats, coords) dims = khats.dims n_data_points = khats.size xdata = np.arange(n_data_points) if isinstance(khats, DataArray): coord_labels = format_coords_as_labels(khats) else: coord_labels = xdata.astype(str) (figsize, ax_labelsize, _, xt_labelsize, linewidth, scaled_markersize) = _scale_fig_size(figsize, textsize) if markersize is None: markersize = scaled_markersize**2 # s in scatter plot mus be markersize square # for dots to have the same size kwargs = matplotlib_kwarg_dealiaser(kwargs, "scatter") kwargs.setdefault("s", markersize) kwargs.setdefault("marker", "+") color_mapping = None cmap = None if isinstance(color, str): if color in dims: colors, color_mapping = color_from_dim(khats, color) cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) rgba_c = cmap(colors) else: legend = False rgba_c = to_rgba_array(np.full(n_data_points, color)) else: legend = False try: rgba_c = to_rgba_array(color) except ValueError: cmap_name = kwargs.get("cmap", plt.rcParams["image.cmap"]) cmap = getattr(cm, cmap_name) rgba_c = cmap(color) khats = khats if isinstance(khats, np.ndarray) else khats.values.flatten() alphas = 0.5 + 0.2 * (khats > 0.5) + 0.3 * (khats > 1) rgba_c[:, 3] = alphas rgba_c = vectorized_to_hex(rgba_c) plot_khat_kwargs = dict( hover_label=hover_label, hover_format=hover_format, ax=ax, figsize=figsize, xdata=xdata, khats=khats, rgba_c=rgba_c, kwargs=kwargs, annotate=annotate, coord_labels=coord_labels, ax_labelsize=ax_labelsize, xt_labelsize=xt_labelsize, show_bins=show_bins, linewidth=linewidth, hlines_kwargs=hlines_kwargs, xlabels=xlabels, legend=legend, color_mapping=color_mapping, cmap=cmap, color=color, n_data_points=n_data_points, bin_format=bin_format, backend_kwargs=backend_kwargs, show=show, ) if backend is None: backend = rcParams["plot.backend"] backend = backend.lower() if backend == "bokeh": plot_khat_kwargs.pop("hover_label") plot_khat_kwargs.pop("hover_format") plot_khat_kwargs.pop("kwargs") plot_khat_kwargs.pop("ax_labelsize") plot_khat_kwargs.pop("xt_labelsize") plot_khat_kwargs.pop("hlines_kwargs") plot_khat_kwargs.pop("xlabels") plot_khat_kwargs.pop("legend") plot_khat_kwargs.pop("color_mapping") plot_khat_kwargs.pop("cmap") plot_khat_kwargs.pop("color") # TODO: Add backend kwargs plot = get_plotting_function("plot_khat", "khatplot", backend) axes = plot(**plot_khat_kwargs) return axes
def get_colors(c, num): """Stretch the color argument to provide the required number num""" return _backports.broadcast_to( mcolors.to_rgba_array(c) if len(c) else [0, 0, 0, 0], (num, 4))
def plot_scatter(adata, color=None, use_raw=None, sort_order=True, edges=False, edges_width=0.1, edges_color='grey', arrows=False, arrows_kwds=None, basis=None, groups=None, components=None, projection='2d', color_map=None, palette=None, size=None, frameon=None, legend_fontsize=None, legend_fontweight='bold', legend_loc='right margin', ncols=4, hspace=0.25, wspace=None, title=None, show=None, save=None, ax=None, return_fig=None, **kwargs): sanitize_anndata(adata) if color_map is not None: kwargs['cmap'] = color_map if size is not None: kwargs['s'] = size if projection == '3d': from mpl_toolkits.mplot3d import Axes3D args_3d = {'projection': '3d'} else: args_3d = {} if adata.raw is not None and use_raw is None: use_raw = True else: use_raw = False if wspace is None: # try to set a wspace that is not too large or too small given the # current figure size wspace = 0.75 / rcParams['figure.figsize'][0] + 0.02 if adata.raw is None and use_raw is True: raise ValueError("`use_raw` is set to True but annData object does not have raw. " "Please check.") #### # get the points position and the components list (only if components is not 'None) data_points, components_list = _get_data_points(adata, basis, projection, components) ### # setup layout. Most of the code is for the case when multiple plots are required # 'color' is a list of names that want to be plotted. Eg. ['Gene1', 'louvain', 'Gene2']. # component_list is a list of components [[0,1], [1,2]] if (isinstance(color, list) and len(color) > 1) or len(components_list) > 1: if ax is not None: raise ValueError("When plotting multiple panels (each for a given value of 'color' " "a given ax can not be used") # change from None to empty list if isinstance(color, str) or color is None: color = [color] if len(components_list) == 0: components_list = [None] multi_panel = True # each plot needs to be its own panel from matplotlib import gridspec # set up the figure num_panels = len(color) * len(components_list) n_panels_x = ncols n_panels_y = np.ceil(num_panels / n_panels_x).astype(int) # each panel will have the size of rcParams['figure.figsize'] fig = pl.figure(figsize=(n_panels_x * rcParams['figure.figsize'][0] * (1 + wspace), n_panels_y * rcParams['figure.figsize'][1])) left = 0.2 / n_panels_x bottom = 0.13 / n_panels_y gs = gridspec.GridSpec(nrows=n_panels_y, ncols=n_panels_x, left=left, right=1-(n_panels_x-1)*left-0.01/n_panels_x, bottom=bottom, top=1-(n_panels_y-1)*bottom-0.1/n_panels_y, hspace=hspace, wspace=wspace) else: # this case handles color='variable' and color=['variable'], which are the same if isinstance(color, str) or color is None: color = [color] if len(components_list) == 0: components_list = [None] multi_panel = False if ax is None: fig = pl.figure() ax = fig.add_subplot(111, **args_3d) ### # make the plots axs = [] import itertools idx_components = range(len(components_list)) # use itertools.product to make a plot for each color and for each component # For example if color=[gene1, gene2] and components=['1,2, '2,3']. # The plots are: [color=gene1, components=[1,2], color=gene1, components=[2,3], # color=gene2, components = [1, 2], color=gene2, components=[2,3]] for count, (value_to_plot, component_idx) in enumerate(itertools.product(color, idx_components)): color_vector, categorical = _get_color_values(adata, value_to_plot, groups=groups, palette=palette, use_raw=use_raw) # check if higher value points should be plot on top if sort_order is True and value_to_plot is not None and categorical is False: order = np.argsort(color_vector) color_vector = color_vector[order] _data_points = data_points[component_idx][order, :] else: _data_points = data_points[component_idx] # if plotting multiple panels, get the ax from the grid spec # else use the ax value (either user given or created previously) if multi_panel is True: ax = pl.subplot(gs[count], **args_3d) axs.append(ax) if frameon is False: ax.axis('off') if title is None and value_to_plot is not None: ax.set_title(value_to_plot) else: ax.set_title(title) if 's' not in kwargs: kwargs['s'] = 120000 / _data_points.shape[0] # make the scatter plot if projection == '3d': cax= ax.scatter(_data_points[:, 0], _data_points[:, 1], _data_points[:, 2], marker=".", c=color_vector, rasterized=settings._vector_friendly, **kwargs) else: c = None try: c = mcolors.to_rgba_array(color_vector) except Exception as e: print( '[WARN] Could not set color due to "%s"' % e ) pass cax= ax.scatter(_data_points[:, 0], _data_points[:, 1], marker=".", c=c, rasterized=settings._vector_friendly, **kwargs) # remove y and x ticks ax.set_yticks([]) ax.set_xticks([]) if projection == '3d': ax.set_zticks([]) # set default axis_labels name = _basis2name(basis) if components is not None: axis_labels = [name + str(x + 1) for x in components_list[component_idx]] elif projection == '3d': axis_labels = [name + str(x + 1) for x in range(3)] else: axis_labels = [name + str(x + 1) for x in range(2)] ax.set_xlabel(axis_labels[0]) ax.set_ylabel(axis_labels[1]) if projection == '3d': # shift the label closer to the axis ax.set_zlabel(axis_labels[2], labelpad=-7) ax.autoscale_view() if edges: utils.plot_edges(ax, adata, basis, edges_width, edges_color) if arrows: utils.plot_arrows(ax, adata, basis, arrows_kwds) if value_to_plot is None: # if only dots were plotted without an associated value # there is not need to plot a legend or a colorbar continue _add_legend_or_colorbar(adata, ax, cax, categorical, value_to_plot, legend_loc, _data_points, legend_fontweight, legend_fontsize, groups, multi_panel) if return_fig is True: return fig axs = axs if multi_panel else ax utils.savefig_or_show(basis, show=show, save=save) if show is False: return axs
def generate_facecolors(x, y, z, dx, dy, dz, color): """Generates shaded facecolors for shaded bars. This is here to work around a Matplotlib bug where alpha does not work in Bar3D. Args: x (array_like): The x- coordinates of the anchor point of the bars. y (array_like): The y- coordinates of the anchor point of the bars. z (array_like): The z- coordinates of the anchor point of the bars. dx (array_like): Width of bars. dy (array_like): Depth of bars. dz (array_like): Height of bars. color (array_like): sequence of valid color specifications, optional Returns: list: Shaded colors for bars. Raises: ImportError: If matplotlib is not installed """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed. To install, run ' '"pip install matplotlib".') import matplotlib.colors as mcolors cuboid = np.array([ # -z ( (0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), ), # +z ( (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1), ), # -y ( (0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1), ), # +y ( (0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0), ), # -x ( (0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0), ), # +x ( (1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1), ), ]) # indexed by [bar, face, vertex, coord] polys = np.empty(x.shape + cuboid.shape) # handle each coordinate separately for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]: p = p[..., np.newaxis, np.newaxis] dp = dp[..., np.newaxis, np.newaxis] polys[..., i] = p + dp * cuboid[..., i] # collapse the first two axes polys = polys.reshape((-1, ) + polys.shape[2:]) facecolors = [] if len(color) == len(x): # bar colors specified, need to expand to number of faces for c in color: facecolors.extend([c] * 6) else: # a single color specified, or face colors specified explicitly facecolors = list(mcolors.to_rgba_array(color)) if len(facecolors) < len(x): facecolors *= (6 * len(x)) normals = _generate_normals(polys) return _shade_colors(facecolors, normals)
def _is_light(color): """Determines if a color (or each of a sequence of colors) is light (as opposed to dark). Based on ITU BT.601 luminance formula (see https://stackoverflow.com/a/596241).""" rgbaArr = colors.to_rgba_array(color) return rgbaArr[:,:3].dot((.299, .587, .114)) > .5
def first_color(colors): colors = mcolors.to_rgba_array(colors) if len(colors): return colors[0] else: return "none"
def _i_mtv(self, data, wcs, title, isMask): """Internal routine to display an Image or Mask on a DS9 display""" title = str(title) if title else "" dataArr = data.getArray() if isMask: maskPlanes = data.getMaskPlaneDict() nMaskPlanes = max(maskPlanes.values()) + 1 planes = {} # build inverse dictionary for key in maskPlanes: planes[maskPlanes[key]] = key planeList = range(nMaskPlanes) maskArr = np.zeros_like(dataArr, dtype=np.int32) colors = ['black'] colorGenerator = self.display.maskColorGenerator(omitBW=True) for p in planeList: color = self.display.getMaskPlaneColor(planes[p]) if p in planes else None if not color: # none was specified color = next(colorGenerator) colors.append(color) # # Set the maskArr image to be an index into our colour map (cmap; see below) # for i, p in enumerate(planeList): color = colors[i] if color.lower() == "ignore": continue maskArr[(dataArr & (1 << p)) != 0] += i + 1 # + 1 as we set colors[0] to black # # Convert those colours to RGBA so we can have per-mask-plane transparency # and build a colour map # colors = mpColors.to_rgba_array(colors) colors[0][3] = 0.0 # it's black anyway for i, p in enumerate(planeList): colors[i + 1][3] = 1 - self._getMaskTransparency(planes[p] if p in planes else None) dataArr = maskArr cmap = mpColors.ListedColormap(colors) norm = mpColors.NoNorm() else: cmap = pyplot.cm.gray norm = self._normalize ax = self._figure.gca() bbox = data.getBBox() ax.imshow(dataArr, origin='lower', interpolation='nearest', extent=(bbox.getBeginX() - 0.5, bbox.getEndX() - 0.5, bbox.getBeginY() - 0.5, bbox.getEndY() - 0.5), cmap=cmap, norm=norm) if False: if evData: axes = self._figure.get_axes()[0] myText = axes.text(0.05, 1.05, 'Press "return" to show intensity here', transform=axes.transAxes, va='top') global eventHandlers eventHandlers[self._figure] = EventHandler((evData, myText), self._figure) self._figure.canvas.draw_idle()
name for name in mcolors.CSS4_COLORS if f'xkcd:{name}' in mcolors.XKCD_COLORS } fig = plt.figure(figsize=[9, 5]) ax = fig.add_axes([0, 0, 1, 1]) n_groups = 3 n_rows = len(overlap) // n_groups + 1 for j, color_name in enumerate(sorted(overlap)): css4 = mcolors.CSS4_COLORS[color_name] xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper() # Pick text colour based on perceived luminance. rgba = mcolors.to_rgba_array([css4, xkcd]) luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2] css4_text_color = 'k' if luma[0] > 0.5 else 'w' xkcd_text_color = 'k' if luma[1] > 0.5 else 'w' col_shift = (j // n_rows) * 3 y_pos = j % n_rows text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None) ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4)) ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd)) ax.text(0.5 + col_shift, y_pos + .7, css4, color=css4_text_color, ha='center', **text_args)