df_temp_mon temps_normed = df_temp_mon.Normalized.values years = np.arange(1899,2020) years elements = len(df_temp_mon) x_lbls = np.arange(elements) y_vals = temps_normed / (len(df_temp_mon) - 1) y_vals2 = np.full(elements, 1) bar_wd = 1 my_cmap = plt.cm.coolwarm #choose colormap to use for bars norm = Normalize(vmin=0, vmax=1.) def colorval(num): return my_cmap(norm(num)) fig=plt.figure(figsize=(22,5)) #plt.axis('off') plt.axis('tight') #Plot warming stripes. Change y_vals2 to y_vals to plot stripes under the line only. plt.bar(x_lbls, y_vals2, color = list(map(colorval, temps_normed)), width=1.0, edgecolor = "none") #plt.colorbar() plt.plot(x_lbls,temps_normed,'k.-',ms=10.) #Plot temperature timeseries. Comment out to only plot stripes #plt.plot((x_lbls + 0.5), y_vals - 0.002, color='black', linewidth=2)
def plot_cov(cov, info, exclude=(), colorbar=True, proj=False, show_svd=True, show=True, verbose=None): """Plot Covariance data. Parameters ---------- cov : instance of Covariance The covariance matrix. info: dict Measurement info. exclude : list of string | str List of channels to exclude. If empty do not exclude any channel. If 'bads', exclude info['bads']. colorbar : bool Show colorbar or not. proj : bool Apply projections or not. show_svd : bool Plot also singular values of the noise covariance for each sensor type. We show square roots ie. standard deviations. show : bool Show figure if True. %(verbose)s Returns ------- fig_cov : instance of matplotlib.figure.Figure The covariance plot. fig_svd : instance of matplotlib.figure.Figure | None The SVD spectra plot of the covariance. See Also -------- mne.compute_rank Notes ----- For each channel type, the rank is estimated using :func:`mne.compute_rank`. .. versionchanged:: 0.19 Approximate ranks for each channel type are shown with red dashed lines. """ from ..cov import Covariance import matplotlib.pyplot as plt from matplotlib.colors import Normalize if exclude == 'bads': exclude = info['bads'] info = pick_info(info, pick_channels(info['ch_names'], cov['names'], exclude)) del exclude picks_list = \ _picks_by_type(info, meg_combined=False, ref_meg=False, exclude=()) picks_by_type = dict(picks_list) ch_names = [n for n in cov.ch_names if n in info['ch_names']] ch_idx = [cov.ch_names.index(n) for n in ch_names] info_ch_names = info['ch_names'] idx_by_type = defaultdict(list) for ch_type, sel in picks_by_type.items(): idx_by_type[ch_type] = [ch_names.index(info_ch_names[c]) for c in sel if info_ch_names[c] in ch_names] idx_names = [(idx_by_type[key], '%s covariance' % DEFAULTS['titles'][key], DEFAULTS['units'][key], DEFAULTS['scalings'][key], key) for key in _DATA_CH_TYPES_SPLIT if len(idx_by_type[key]) > 0] C = cov.data[ch_idx][:, ch_idx] projs = [] if proj: projs = copy.deepcopy(info['projs']) # Activate the projection items for p in projs: p['active'] = True P, ncomp, _ = make_projector(projs, ch_names) if ncomp > 0: logger.info(' Created an SSP operator (subspace dimension' ' = %d)' % ncomp) C = np.dot(P, np.dot(C, P.T)) else: logger.info(' The projection vectors do not apply to these ' 'channels.') fig_cov, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, _, _, _) in enumerate(idx_names): vlim = np.max(np.abs(C[idx][:, idx])) im = axes[0, k].imshow(C[idx][:, idx], interpolation="nearest", norm=Normalize(vmin=-vlim, vmax=vlim), cmap='RdBu_r') axes[0, k].set(title=name) if colorbar: from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(axes[0, k]) cax = divider.append_axes("right", size="5.5%", pad=0.05) plt.colorbar(im, cax=cax, format='%.0e') fig_cov.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.2, 0.26) tight_layout(fig=fig_cov) fig_svd = None if show_svd: fig_svd, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, unit, scaling, key) in enumerate(idx_names): this_C = C[idx][:, idx] s = linalg.svd(this_C, compute_uv=False) this_C = Covariance(this_C, [info['ch_names'][ii] for ii in idx], [], [], 0) this_info = pick_info(info, idx) this_info['projs'] = [] this_rank = compute_rank(this_C, info=this_info) # Protect against true zero singular values s[s <= 0] = 1e-10 * s[s > 0].min() s = np.sqrt(s) * scaling axes[0, k].plot(s, color='k', zorder=3) this_rank = this_rank[key] axes[0, k].axvline(this_rank - 1, ls='--', color='r', alpha=0.5, zorder=4, clip_on=False) axes[0, k].text(this_rank - 1, axes[0, k].get_ylim()[1], 'rank ≈ %d' % (this_rank,), ha='right', va='top', color='r', alpha=0.5, zorder=4) axes[0, k].set(ylabel=u'Noise σ (%s)' % unit, yscale='log', xlabel='Eigenvalue index', title=name, xlim=[0, len(s) - 1]) tight_layout(fig=fig_svd) plt_show(show) return fig_cov, fig_svd
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, arrowstyle='-|>', arrowsize=10, draw_loop=False, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, node_size=300, nodelist=None, node_shape="o", **kwds): """Draw the edges of the graph G. This draws only the edges of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=1.0) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. Note: Arrows will be the same color as edges. arrowstyle : str, optional (default='-|>') For directed graphs, choose the style of the arrow heads. See :py:class: `matplotlib.patches.ArrowStyle` for more options. arrowsize : int, optional (default=10) For directed graphs, choose the size of the arrow head head's length and width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale` for more info. label : [None| string] Label for legend Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edges list of matplotlib.patches.FancyArrowPatch `FancyArrowPatch` instances of the directed edges Depending whether the drawing includes arrows or not. Notes ----- For directed graphs, arrows are drawn at the head end. Arrows can be turned off with keyword arrows=False. Be sure to include `node_size' as a keyword argument; arrows are drawn considering the size of nodes. Examples -------- >>> G = nx.dodecahedral_graph() >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)]) >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> alphas = [0.3, 0.4, 0.5] >>> for i, arc in enumerate(arcs): # change alpha values of arcs ... arc.set_alpha(alphas[i]) Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cbook as cb from matplotlib.colors import colorConverter, Colormap, Normalize from matplotlib.collections import LineCollection from matplotlib.patches import FancyArrowPatch import numpy as np except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: ax = plt.gca() if edgelist is None: edgelist = list(G.edges()) if not edgelist or len(edgelist) == 0: # no edges! return None if nodelist is None: nodelist = list(G.nodes()) # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width, ) else: lw = width if not is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color) == len(edge_pos): if np.alltrue([is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple( [colorConverter.to_rgba(c, alpha) for c in edge_color]) elif np.alltrue([not is_string_like(c) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if np.alltrue( [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]): edge_colors = tuple(edge_color) else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must contain color names or numbers') else: if is_string_like(edge_color) or len(edge_color) == 1: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) else: msg = 'edge_color must be a color or list of one color per edge' raise ValueError(msg) if (not G.is_directed() or not arrows): edge_collection = LineCollection( edge_pos, colors=edge_colors, linewidths=lw, antialiaseds=(1, ), linestyle=style, transOffset=ax.transData, ) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(label) ax.add_collection(edge_collection) # Note: there was a bug in mpl regarding the handling of alpha values # for each line in a LineCollection. It was fixed in matplotlib by # r7184 and r7189 (June 6 2009). We should then not set the alpha # value globally, since the user can instead provide per-edge alphas # now. Only set it globally if provided as a scalar. if cb.is_numlike(alpha): edge_collection.set_alpha(alpha) if edge_colors is None: if edge_cmap is not None: assert (isinstance(edge_cmap, Colormap)) edge_collection.set_array(np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() return edge_collection arrow_collection = None if G.is_directed() and arrows: # Note: Waiting for someone to implement arrow to intersection with # marker. Meanwhile, this works well for polygons with more than 4 # sides and circle. def to_marker_edge(marker_size, marker): if marker in "s^>v<d": # `large` markers need extra space return np.sqrt(2 * marker_size) / 2 else: return np.sqrt(marker_size) / 2 # Draw arrows with `matplotlib.patches.FancyarrowPatch` arrow_collection = [] mutation_scale = arrowsize # scale factor of arrow head arrow_colors = edge_colors if arrow_colors is None: if edge_cmap is not None: assert (isinstance(edge_cmap, Colormap)) else: edge_cmap = plt.get_cmap() # default matplotlib colormap if edge_vmin is None: edge_vmin = min(edge_color) if edge_vmax is None: edge_vmax = max(edge_color) color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax) for i, (src, dst) in enumerate(edge_pos): x1, y1 = src x2, y2 = dst arrow_color = None line_width = None shrink_source = 0 # space from source to tail shrink_target = 0 # space from head to target if cb.iterable(node_size): # many node sizes src_node, dst_node = edgelist[i] index_node = nodelist.index(dst_node) marker_size = node_size[index_node] shrink_target = to_marker_edge(marker_size, node_shape) else: shrink_target = to_marker_edge(node_size, node_shape) if arrow_colors is None: arrow_color = edge_cmap(color_normal(edge_color[i])) elif len(arrow_colors) > 1: arrow_color = arrow_colors[i] else: arrow_color = arrow_colors[0] if len(lw) > 1: line_width = lw[i] else: line_width = lw[0] arrow = FancyArrowPatch((x1, y1), (x2, y2), arrowstyle=arrowstyle, shrinkA=shrink_source, shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, zorder=1) # arrows go behind nodes if draw_loop == False: arrow = arrow arrow_collection.append(arrow) ax.add_patch(arrow) else: cycle_edges = list(nx.simple_cycles(G)) loop_points = [(x, y) for x, y in cycle_edges] for x in loop_points: to_remove = list(G.edges()) half_cycle = to_remove.index(x) second_half = to_remove.index(x[::-1]) if (src in edge_pos[half_cycle][0] and dst in edge_pos[half_cycle][1]) or ( src in edge_pos[second_half][0] and dst in edge_pos[second_half][1]): arrow1 = FancyArrowPatch( (x1, y1), (x2, y2), arrowstyle=arrowstyle, shrinkA=shrink_source, connectionstyle= 'angle3, angleA=28.66', #180/2pi, approx shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, zorder=1) # arrows go behind nodes arrow_collection.append(arrow1) ax.add_patch(arrow1) try: arrow2 = FancyArrowPatch( (x2, y2), (x1, y1), arrowstyle=arrowstyle, shrinkA=shrink_source, connectionstyle='angle3, angleA=28.66', #180/2pi shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, zorder=1) # arrows go behind nodes arrow_collection.append(arrow2) ax.add_patch(arrow2) except nx.NetworkXError: raise else: arrow = arrow arrow_collection.append(arrow) ax.add_patch(arrow) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() return arrow_collection
def information_recovery(pred_labels, comm_size, truth, interlayers, other_parameter, com_op): NMI1 = np.zeros((len(interlayers), len(other_parameter))) ARI1 = np.zeros((len(interlayers), len(other_parameter))) F1S1 = np.zeros((len(interlayers), len(other_parameter))) if truth == 'Scattered': true_labels = generate_ground_truth(comm_size, method='scattered', pad=True, community_operation=com_op) if truth == 'Integrated': true_labels = generate_ground_truth(comm_size, method='integrated', pad=True, community_operation=com_op) for i in range(len(interlayers)): for j in range(len(other_parameter)): NMI1[i][j] = normalized_mutual_info_score( true_labels, list(pred_labels[i * len(other_parameter) + j].astype(int)), average_method='max') ARI1[i][j] = adjusted_rand_score( true_labels, list(pred_labels[i * len(other_parameter) + j].astype(int))) F1S1[i][j] = f1_score(true_labels, list(pred_labels[i * len(other_parameter) + j].astype(int)), average='weighted') fig, ax = plt.subplots(1, 3, figsize=(85, 50)) normalize = Normalize(vmin=0, vmax=1) c = ax[0].imshow(NMI1, origin='lower', interpolation='none', cmap='Reds', aspect='auto', norm=normalize, extent=[ other_parameter[0] - 0.005, other_parameter[-1] + 0.005, interlayers[0] - 0.005, interlayers[-1] + 0.005 ]) c = ax[1].imshow(ARI1, origin='lower', interpolation='none', cmap='Reds', aspect='auto', norm=normalize, extent=[ other_parameter[0] - 0.005, other_parameter[-1] + 0.005, interlayers[0] - 0.005, interlayers[-1] + 0.005 ]) c = ax[2].imshow(F1S1, origin='lower', interpolation='none', cmap='Reds', aspect='auto', norm=normalize, extent=[ other_parameter[0] - 0.005, other_parameter[-1] + 0.005, interlayers[0] - 0.005, interlayers[-1] + 0.005 ]) ax[0].set_title('NMI wrt %s Ground Truth' % truth, fontsize=60) ax[0].set_xlabel('Threshold', fontsize=50) ax[0].set_ylabel('Interlayer Coupling', fontsize=50) ax[0].set_xticks([i * 0.1 for i in range(9)]) ax[0].set_yticks(interlayers) ax[0].tick_params(axis='both', labelsize=30) ax[1].set_title('ARI wrt %s Ground Truth' % truth, fontsize=60) ax[1].set_xlabel('Threshold', fontsize=50) ax[1].set_ylabel('Interlayer Coupling', fontsize=50) ax[1].set_xticks([i * 0.1 for i in range(9)]) ax[1].set_yticks(interlayers) ax[1].tick_params(axis='both', labelsize=30) ax[2].set_title('F1-Score wrt %s Ground Truth' % truth, fontsize=60) ax[2].set_xlabel('Threshold', fontsize=50) ax[2].set_ylabel('Interlayer Coupling', fontsize=50) ax[2].set_xticks([i * 0.1 for i in range(9)]) ax[2].set_yticks(interlayers) ax[2].tick_params(axis='both', labelsize=30) cbar = fig.colorbar(c, ax=ax.flat, orientation='horizontal') cbar.ax.tick_params(labelsize=40) return (fig, ax)
intensity = pin1_intensities[(left_label, right_label)] # shift = pin1_shifts[(left_label,right_label)] wall_center = wall_centers[(left_label, right_label)] wall_normal = wall_normals[(left_label, right_label)] if pin1_orientation: pin1_vector = np.sign(pin1_orientation) * wall_normal # pin1_color = np.array([0.1,0.8,0.2])*np.abs(pin1_orientation) + np.array([1.,1.,1.])*(1.-np.abs(pin1_orientation)) # pin1_edgecolor = np.array([0.0,0.0,0.0])*np.abs(pin1_orientation) + np.array([0.8,0.2,0.2])*(1.-np.abs(pin1_orientation)) # if np.abs(pin1_orientation)==1: # pin1_color = 'chartreuse' # elif np.abs(pin1_orientation)==0.5: # pin1_color = 'gold' # elif np.abs(pin1_orientation)==0.25: # pin1_color = 'peru' pin1_color = mpl.cm.ScalarMappable( cmap='Greens', norm=Normalize(vmin=0, vmax=65535)).to_rgba(intensity) figure.gca().arrow(wall_center[0] - 0.75 * pin1_vector[0], wall_center[1] - 0.75 * pin1_vector[1], pin1_vector[0], pin1_vector[1], head_width=1, head_length=1, edgecolor='k', facecolor=pin1_color, linewidth=1, alpha=np.abs(pin1_orientation)) for label in cell_pin1_vectors.keys(): cell_center = cell_centers[label] # cell_pin1_vector = 2.*microscope_orientation*cell_pin1_vectors[label]
if r < 1: plt.scatter(x, y, color=color_map(np.where(d == d.min())[0])) plt.axis('off') ## linear combination of 5 PC can support som._weights # how many PC can support som._weights Correlation = np.zeros((64, 64)) for i in range(64): for j in range(64): linreg = LinearRegression() model = linreg.fit(pca.components_[0:20].T, som._weights[i, j, :].reshape(1000, 1)) Correlation[i, j] = np.corrcoef( np.dot(model.coef_[0], pca.components_[0:20]), som._weights[i, j, :])[0, 1] plt.imshow(Correlation, norm=Normalize(0, 1), cmap='jet') plt.colorbar() # what meaning of PCs? for pc in range(5): Correlation = np.zeros((64, 64)) for i in range(64): for j in range(64): linreg = LinearRegression() model = linreg.fit(pca.components_[[pc]].T, som._weights[i, j, :].reshape(1000, 1)) Correlation[i, j] = np.corrcoef( np.dot(model.coef_[0], pca.components_[[pc]]), som._weights[i, j, :])[0, 1] plt.figure() plt.title('Correlation of PC%d' % (pc + 1))
def updateFigure(self): self.figure.clear() if (self.imageData is None) and \ (self.pixmapImage is None): return # The axes self.axes = self.figure.add_axes([.15, .15, .75, .8]) if self.config['xaxis'] == 'off': self.axes.xaxis.set_visible(False) else: self.axes.xaxis.set_visible(True) nLabels = self.config['nxlabels'] if nLabels not in ['Auto', 'auto', '0', 0]: self.axes.xaxis.set_major_locator(MaxNLocator(nLabels)) else: self.axes.xaxis.set_major_locator(AutoLocator()) if self.config['yaxis'] == 'off': self.axes.yaxis.set_visible(False) else: self.axes.yaxis.set_visible(True) nLabels = self.config['nylabels'] if nLabels not in ['Auto', 'auto', '0', 0]: self.axes.yaxis.set_major_locator(MaxNLocator(nLabels)) else: self.axes.yaxis.set_major_locator(AutoLocator()) if self.pixmapImage is not None: self._updatePixmapFigure() return interpolation = self.config['interpolation'] origin = self.config['origin'] cmap = self.__temperatureCmap ccmap = cm.gray if self.config['colormap'] in ['grey', 'gray']: cmap = cm.gray ccmap = self.__temperatureCmap elif self.config['colormap'] in ['yarg', 'yerg']: cmap = self.__reversedGrayCmap ccmap = self.__temperatureCmap elif self.config['colormap'] == 'jet': cmap = cm.jet elif self.config['colormap'] == 'hot': cmap = cm.hot elif self.config['colormap'] == 'cool': cmap = cm.cool elif self.config['colormap'] == 'copper': cmap = cm.copper elif self.config['colormap'] == 'spectral': cmap = cm.spectral elif self.config['colormap'] == 'hsv': cmap = cm.hsv elif self.config['colormap'] == 'rainbow': cmap = cm.gist_rainbow elif self.config['colormap'] == 'red': cmap = self.__redCmap elif self.config['colormap'] == 'green': cmap = self.__greenCmap elif self.config['colormap'] == 'blue': cmap = self.__blueCmap elif self.config['colormap'] == 'temperature': cmap = self.__temperatureCmap elif self.config['colormap'] == 'paired': cmap = cm.Paired elif self.config['colormap'] == 'paired_r': cmap = cm.Paired_r elif self.config['colormap'] == 'pubu': cmap = cm.PuBu elif self.config['colormap'] == 'pubu_r': cmap = cm.PuBu_r elif self.config['colormap'] == 'rdbu': cmap = cm.RdBu elif self.config['colormap'] == 'rdbu_r': cmap = cm.RdBu_r elif self.config['colormap'] == 'gist_earth': cmap = cm.gist_earth elif self.config['colormap'] == 'gist_earth_r': cmap = cm.gist_earth_r elif self.config['colormap'] == 'blues': cmap = cm.Blues elif self.config['colormap'] == 'blues_r': cmap = cm.Blues_r elif self.config['colormap'] == 'ylgnbu': cmap = cm.YlGnBu elif self.config['colormap'] == 'ylgnbu_r': cmap = cm.YlGnBu_r else: print("Unsupported colormap %s" % self.config['colormap']) if self.config['extent'] is None: h, w = self.imageData.shape x0 = self.config['xorigin'] y0 = self.config['yorigin'] w = w * self.config['xpixelsize'] h = h * self.config['ypixelsize'] if origin == 'upper': extent = (x0, w + x0, h + y0, y0) else: extent = (x0, w + x0, y0, h + y0) else: extent = self.config['extent'] vlimits = self.__getValueLimits() if vlimits is None: imageData = self.imageData vmin = self.imageData.min() vmax = self.imageData.max() else: vmin = min(vlimits[0], vlimits[1]) vmax = max(vlimits[0], vlimits[1]) imageData = self.imageData.clip(vmin, vmax) if self.config['linlogcolormap'] != 'linear': if vmin <= 0: if vmax > 0: vmin = min(imageData[imageData > 0]) else: vmin = 0.0 vmax = 1.0 self._image = self.axes.imshow(imageData.clip(vmin, vmax), interpolation=interpolation, origin=origin, cmap=cmap, extent=extent, norm=LogNorm(vmin, vmax)) else: self._image = self.axes.imshow(imageData, interpolation=interpolation, origin=origin, cmap=cmap, extent=extent, norm=Normalize(vmin, vmax)) ylim = self.axes.get_ylim() if self.config['colorbar'] is not None: barorientation = self.config['colorbar'] if barorientation == "vertical": xlim = self.axes.get_xlim() deltaX = abs(xlim[1] - xlim[0]) deltaY = abs(ylim[1] - ylim[0]) ratio = deltaY / float(deltaX) shrink = ratio self._colorbar = self.figure.colorbar( self._image, fraction=0.046, pad=0.04, #shrink=shrink, aspect=20 * shrink, orientation=barorientation) if ratio < 0.51: nTicks = 5 if ratio < 0.2: nTicks = 3 try: tick_locator = MaxNLocator(nTicks) self._colorbar.locator = tick_locator self._colorbar.update_ticks() except: print("Colorbar error", sys.exc_info()) pass else: self._colorbar = self.figure.colorbar( self._image, orientation=barorientation) #contour plot if self.config['contour'] != 'off': dataMin = imageData.min() dataMax = imageData.max() ncontours = int(self.config['contourlevels']) levels = (numpy.arange(ncontours)) *\ (dataMax - dataMin)/float(ncontours) contourlinewidth = int(self.config['contourlinewidth']) / 10. if self.config['contour'] == 'filled': self._contour = self.axes.contourf(imageData, levels, origin=origin, cmap=ccmap, extent=extent) else: self._contour = self.axes.contour(imageData, levels, origin=origin, cmap=ccmap, linewidths=contourlinewidth, extent=extent) if self.config['contourlabels'] != 'off': self.axes.clabel(self._contour, fontsize=9, inline=1, fmt=self.config['contourlabelformat']) if 0 and self.config['colorbar'] is not None: if barorientation == 'horizontal': barorientation = 'vertical' else: barorientation = 'horizontal' self._ccolorbar = self.figure.colorbar( self._contour, orientation=barorientation, extend='both') self.__postImage(ylim)
block = np.floor(np.array(point) / B) #first component is col, second component is row print(block) col = block[0, 0] col = int(col) row = block[0, 1] row = int(row) plt.plot([B * col, B * col + B, B * col + B, B * col, B * col], [B * row, B * row, B * row + B, B * row + B, B * row]) plt.axis([0, w, h, 0]) plt.title("Original Image") plt.figure() plt.subplot(1, 2, 1) selectedImg = img1[row * B:(row + 1) * B, col * B:(col + 1) * B] N255 = Normalize(0, 255) #Normalization object, used by imshow() plt.imshow(selectedImg, cmap="gray", norm=N255, interpolation='nearest') plt.title("Image in selected Region") plt.subplot(1, 2, 2) selectedTrans = Trans[row * B:(row + 1) * B, col * B:(col + 1) * B] plt.imshow(selectedTrans, cmap=cm.jet, interpolation='nearest') plt.colorbar(shrink=0.5) plt.title("DCT transform of selected Region") back0 = np.zeros((h, w), np.float32) for row in range(blocksV): for col in range(blocksH): currentblock = cv2.idct(Trans[row * B:(row + 1) * B, col * B:(col + 1) * B]) back0[row * B:(row + 1) * B, col * B:(col + 1) * B] = currentblock
def get_random_colourscale(max_fitness): cs = ColourScale(all_clones_noisy=False, colourmaps=random_colour, name='random') return cs # An example colourscale which plots type 0 cells and type 1 cells as yellow/green Key1 = namedtuple('Key1', ['label']) COLOURSCALE_EXAMPLE1 = ColourScale(name='Single Green Mutant', all_clones_noisy=True, colourmaps={ Key1(label=0): cm.ScalarMappable( norm=Normalize(vmin=0, vmax=2), cmap=cm.YlOrBr).to_rgba, Key1(label=1): cm.Greens }) # An example colourscale which plots non-synonymous clones as red and synonymous as blue # Initial clones are beige Key2 = namedtuple('Key2', ['ns', 'initial']) COLOURSCALE_EXAMPLE2 = ColourScale(name='S vs NS', all_clones_noisy=True, colourmaps={ Key2(ns=True, initial=False): cm.Reds, Key2(ns=False, initial=False): cm.Blues,
def plot_stack(npixels, hp, cr, snr, filename=None, scale=None): lon, lat = hp.healpix_to_lonlat(npixels) boundaries = hp.boundaries_lonlat(npixels, 1) patches = [] for blon, blat in zip(*boundaries): patches.append( Polygon(np.array([blon.value, blat.value]).T, closed=True)) if not scale: vmin_cr, vmax_cr = cr.flatten().min(), cr.flatten().max() vmin_snr, vmax_snr = snr.flatten().min(), snr.flatten().max() scale = [vmin_cr, vmax_cr, vmin_snr, vmax_snr] else: vmin_cr, vmax_cr = scale[0], scale[1] vmin_snr, vmax_snr = scale[2], scale[3] norm_cr = Normalize(vmin=vmin_cr, vmax=vmax_cr) norm_snr = Normalize(vmin=vmin_snr, vmax=vmax_snr) fig, axs = plt.subplots(2, 3, constrained_layout=False, figsize=(5.5, 4)) for i, eband in enumerate(["6", "7", "8"]): # Count-rate "images" pcm_cr = axs[0, i].scatter(lon, lat, c=cr[:, i], s=1, vmin=vmin_cr, vmax=vmax_cr) p = PatchCollection(patches, alpha=1) p.set_array(cr[:, i]) p.set_norm(norm_cr) axs[0, i].add_collection(p) axs[0, i].set_title(f"Energy band {eband}") axs[0, i].set_xticks([]) axs[0, i].set_yticks([]) # signal-to-noise ratio "images" pcm_snr = axs[1, i].scatter(lon, lat, c=snr[:, i], s=1, vmin=vmin_snr, vmax=vmax_snr) p = PatchCollection(patches, alpha=1) p.set_array(snr[:, i]) p.set_norm(norm_snr) axs[1, i].add_collection(p) axs[1, i].set_xticks([]) axs[1, i].set_yticks([]) if i == 0: axs[0, i].set_ylabel("Stack net CR (median)") axs[1, i].set_ylabel("Stack SNR (median)") plt.tight_layout() fig.colorbar(pcm_cr, ax=axs[0, :], shrink=0.6, location='bottom', pad=0.02) fig.colorbar(pcm_snr, ax=axs[1, :], shrink=0.6, location='bottom', pad=0.02) if filename: fig.savefig(filename, bbox_inches='tight', pad_inches=0) plt.close() else: plt.show() return scale
log, summary = [r"{0:28s}".format(spec)], [] for i, d in enumerate(dists): weights = np.ones_like(d.data) / len(d.data) ax = plt.subplot(3, 3, (4 * i) + 1) # plt.tick_params(labelsize=10) N, bins, patches = plt.hist(d.data, color="b", ec="k", bins=30, range=tuple(lims[i]), normed=True, edgecolor="k", histtype='bar', linewidth=1.) fracs = N.astype(float) / N.max() norm = Normalize(-.2 * fracs.max(), 1.5 * fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = cm.gray_r(norm(thisfrac)) thispatch.set_facecolor(color) thispatch.set_edgecolor("w") x = np.linspace(d.data.min(), d.data.max(), 100) tot = np.zeros_like(x) # for m,w,c in zip(d.gmm.best.means_, d.gmm.best.weights_, # d.gmm.best.covars_): # y = w * normpdf(x, m, np.sqrt(c))[0] # ax.plot(x, y, "--b") # tot += y # ax.plot(x,tot, "-b", lw=2) # pdf = np.exp(logprob) # pdf_individual = responsibilities * pdf[:, np.newaxis] # print pdf_individual
def make_plot(): # Load data loss_yearly = xr.open_dataset( '../data/results/xu/forest_loss_effect_year_0207.nc') trend = xr.open_dataset( '../data/results/xu/forest_loss_impact_based_on_trend_0207.nc') loss = xr.open_dataset('../data/results/xu/MODIS_loss_effect_0207.nc') # loss_yearly['time']=list(range(2002,2019))# temporaray fix for time # floss=xr.open_dataset('../data/results/forestloss_2018_05deg.nc') # old data # floss=xr.open_dataset('../data/results/net_loss_2018_05deg.nc') floss = xr.open_dataset('../data/results/loss_2018_05deg.nc') # gross loss floss_diff_yearly = xr.open_dataset( '../data/results/xu/loss_diff_yearly_05deg.nc') floss_base_diff = xr.open_dataset( '../data/results/xu/loss_basetree_diff_05deg.nc') tree_diff = floss_base_diff.tree_diff - floss_diff_yearly.loss_diff.cumsum( dim='time') # Baseyear delta tree - delta loss to get tree diff # tree_diff.time.values=range(2001,2019,1) # jet cmap mycmap = get_myjet_cmap() fig = plt.figure(figsize=[10, 10]) fig, axs = plt.subplots(ncols=4, nrows=6, figsize=[12, 12]) gs = axs[1, 2].get_gridspec() # remove the underlying axes for ax in axs[0:6, 0:4].flatten(): ax.remove() # https://matplotlib.org/3.1.3/gallery/subplots_axes_and_figures/gridspec_and_subplots.html axbig1 = fig.add_subplot(gs[0:2, 0:2], projection=ccrs.PlateCarree()) axbig2 = fig.add_subplot(gs[0:2, 2:4], projection=ccrs.PlateCarree()) floss.forest_loss.plot(ax=axbig1, cmap='hot', rasterized=True, add_colorbar=False) loss.loss_effect.plot(ax=axbig2, cmap=mycmap, vmin=-0.15, vmax=0.15, rasterized=True, add_colorbar=False) axbig1.set_extent([-180, 180, -60, 80]) axbig2.set_extent([-180, 180, -60, 80]) axbig1.coastlines() axbig2.coastlines() # Move big plot up axbig1.set_position([ axbig1.get_position().x0, axbig1.get_position().y0 + 0.035, axbig1.get_position().width, axbig1.get_position().height ]) axbig2.set_position([ axbig2.get_position().x0, axbig2.get_position().y0 + 0.035, axbig2.get_position().width, axbig2.get_position().height ]) # Plot region boundary plot_region_box(axbig1, [-20, 0, -70, -40]) # Amazon plot_region_box(axbig1, [-5, 15, 95, 125]) # Indonesia plot_region_box(axbig1, [55, 70, 115, 137.5]) # East Seberia plot_region_box(axbig1, [25, 40, -95, -72.5]) # SouthEast USA plot_region_box(axbig2, [-20, 0, -70, -40]) # Amazon plot_region_box(axbig2, [-5, 15, 95, 125]) # Indonesia plot_region_box(axbig2, [55, 70, 115, 137.5]) # East Seberia plot_region_box(axbig2, [25, 40, -95, -72.5]) # SouthEast USA axbig1.set_title('Forest loss', fontsize=14) axbig2.set_title('Forest loss impact on cloud cover', fontsize=14) # Add colorbar to big plot cbarbig1_pos = [ axbig1.get_position().x0, axbig1.get_position().y0 - 0.025, axbig1.get_position().width, 0.01 ] caxbig1 = fig.add_axes(cbarbig1_pos) cmap0, norm = norm_cmap(cmap='hot', vmin=-0.8, vmax=0) cbbig1 = mpl.colorbar.ColorbarBase( ax=caxbig1, cmap=cmap0.cmap, norm=norm, orientation='horizontal', ticks=np.arange(-0.8, 0, 0.2)) #cmap=plt.get_cmap('hot') cbbig1.ax.set_yticklabels(np.arange(-0.8, 0.1, 0.2), fontsize=10) cbbig1.set_label('Forest loss fraction', fontsize=12) cbarbig2_pos = [ axbig2.get_position().x0, axbig2.get_position().y0 - 0.025, axbig2.get_position().width, 0.01 ] caxbig2 = fig.add_axes(cbarbig2_pos) # cmap0, norm = norm_cmap(cmap='hot', vmin=-0.8, vmax=0) cbbig2 = mpl.colorbar.ColorbarBase(ax=caxbig2, cmap=mycmap, norm=Normalize(vmin=-0.25, vmax=0.25), orientation='horizontal', ticks=np.arange(-0.2, 0.21, 0.1)) cbbig2.ax.set_yticklabels(np.arange(-0.2, 0.21, 0.1), fontsize=10) cbbig2.set_label(r'$\Delta\mathrm{Cloud_{loss}}$', fontsize=12) # Regional zoomed map ax11 = fig.add_subplot(6, 4, 1 + 8, projection=ccrs.PlateCarree()) ax12 = fig.add_subplot(6, 4, 2 + 8, projection=ccrs.PlateCarree()) ax13 = fig.add_subplot(6, 4, 3 + 8, projection=ccrs.PlateCarree()) ax14 = fig.add_subplot(6, 4, 4 + 8) ax21 = fig.add_subplot(6, 4, 5 + 8, projection=ccrs.PlateCarree()) ax22 = fig.add_subplot(6, 4, 6 + 8, projection=ccrs.PlateCarree()) ax23 = fig.add_subplot(6, 4, 7 + 8, projection=ccrs.PlateCarree()) ax24 = fig.add_subplot(6, 4, 8 + 8) ax31 = fig.add_subplot(6, 4, 9 + 8, projection=ccrs.PlateCarree()) ax32 = fig.add_subplot(6, 4, 10 + 8, projection=ccrs.PlateCarree()) ax33 = fig.add_subplot(6, 4, 11 + 8, projection=ccrs.PlateCarree()) ax34 = fig.add_subplot(6, 4, 12 + 8) ax41 = fig.add_subplot(6, 4, 13 + 8, projection=ccrs.PlateCarree()) ax42 = fig.add_subplot(6, 4, 14 + 8, projection=ccrs.PlateCarree()) ax43 = fig.add_subplot(6, 4, 15 + 8, projection=ccrs.PlateCarree()) ax44 = fig.add_subplot(6, 4, 16 + 8) ax14sec = ax14.twinx() ax24sec = ax24.twinx() ax34sec = ax34.twinx() ax44sec = ax44.twinx() # Amazon plot_pcolor_map( floss.forest_loss.where(floss.forest_loss != 0).loc[-20:0, -70:-40], ax=ax11, vminmax=[-0.8, 0], cmap='hot') plot_pcolor_map( loss.loss_effect.where(floss.forest_loss < -0.05).loc[-20:0, -70:-40], ax=ax12, vminmax=[-0.15, 0.15], cmap=mycmap) plot_pcolor_map( trend.loss_impact.where(floss.forest_loss < -0.05).loc[-20:0, -70:-40], ax=ax13, vminmax=[-0.015, 0.015], cmap=mycmap) plot_yearly_change(loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, -20:0, -70:-40], ax=ax14) plot_trend_line( ax14, loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, -20:0, -70:-40]) plot_yearly_tree( tree_diff.where(floss.forest_loss < -0.05).loc[-20:0, -70:-40, 2002::], ax14sec) set_lat_lon(ax11, range(-70, -39, 10), range(-20, 1, 10), label=True) set_lat_lon(ax12, range(-70, -39, 10), range(-20, 1, 10)) set_lat_lon(ax13, range(-70, -39, 10), range(-20, 1, 10)) # Indonisia plot_pcolor_map( floss.forest_loss.where(floss.forest_loss != 0).loc[-5:15, 95:125], ax=ax21, vminmax=[-0.8, 0], cmap='hot') plot_pcolor_map( loss.loss_effect.where(floss.forest_loss < -0.05).loc[-5:15, 95:125], ax=ax22, vminmax=[-0.15, 0.15], cmap=mycmap) plot_pcolor_map( trend.loss_impact.where(floss.forest_loss < -0.05).loc[-5:15, 95:125], ax=ax23, vminmax=[-0.015, 0.015], cmap=mycmap) plot_yearly_change(loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, -5:15, 95:125], ax=ax24) plot_trend_line(ax24, loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, -5:15, 95:125], x=0.45) plot_yearly_tree( tree_diff.where(floss.forest_loss < -0.05).loc[-5:15, 95:125, 2002::], ax24sec) set_lat_lon(ax21, range(95, 126, 10), range(-5, 14, 10), label=True) set_lat_lon(ax22, range(95, 126, 10), range(-5, 14, 10)) set_lat_lon(ax23, range(95, 126, 10), range(-5, 14, 10)) # Southeast America plot_pcolor_map( floss.forest_loss.where(floss.forest_loss != 0).loc[25:40, -95:-72.5], ax=ax31, vminmax=[-0.8, 0], cmap='hot') plot_pcolor_map( loss.loss_effect.where(floss.forest_loss < -0.05).loc[25:40, -95:-72.5], ax=ax32, vminmax=[-0.15, 0.15], cmap=mycmap) plot_pcolor_map( trend.loss_impact.where(floss.forest_loss < -0.05).loc[25:40, -95:-72.5], ax=ax33, vminmax=[-0.015, 0.015], cmap=mycmap) plot_yearly_change(loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, 25:40, -95:-72.5], ax=ax34) plot_trend_line(ax34, loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, 25:40, -95:-72.5], x=0.38) plot_yearly_tree( tree_diff.where(floss.forest_loss < -0.05).loc[25:40, -95:-72.5, 2002::], ax34sec) set_lat_lon(ax31, range(-95, -73, 10), range(25, 41, 10), label=True) set_lat_lon(ax32, range(-95, -73, 10), range(25, 41, 10)) set_lat_lon(ax33, range(-95, -73, 10), range(25, 41, 10)) # East Siberia plot_pcolor_map( floss.forest_loss.where(floss.forest_loss != 0).loc[55:70, 115:137.5], ax=ax41, vminmax=[-0.8, 0], cmap='hot') plot_pcolor_map( loss.loss_effect.where(floss.forest_loss < -0.05).loc[55:70, 115:137.5], ax=ax42, vminmax=[-0.15, 0.15], cmap=mycmap) plot_pcolor_map( trend.loss_impact.where(floss.forest_loss < -0.05).loc[55:70, 115:137.5], ax=ax43, vminmax=[-0.015, 0.015], cmap=mycmap) plot_yearly_change(loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, 55:70, 115:137.5], ax=ax44) plot_trend_line(ax44, loss_yearly.forest_loss_effect.where( floss.forest_loss < -0.05).loc[2002:2018, 55:70, 115:137.5], x=0.3) plot_yearly_tree( tree_diff.where(floss.forest_loss < -0.05).loc[55:70, 115:137.5, 2002::], ax44sec) set_lat_lon(ax41, range(115, 137, 10), range(55, 71, 10), label=True) set_lat_lon(ax42, range(115, 137, 10), range(55, 71, 10)) set_lat_lon(ax43, range(115, 137, 10), range(55, 71, 10)) ax44.set_yticks(np.arange(-0.6, 0.01, 0.3)) # Fix panel D time series axis size ax14.set_position([ ax14.get_position().x0, ax11.get_position().y0, ax11.get_position().width, ax11.get_position().height ]) ax24.set_position([ ax24.get_position().x0, ax21.get_position().y0, ax21.get_position().width, ax21.get_position().height ]) ax34.set_position([ ax34.get_position().x0, ax31.get_position().y0, ax31.get_position().width, ax31.get_position().height ]) ax44.set_position([ ax44.get_position().x0, ax41.get_position().y0, ax41.get_position().width, ax41.get_position().height ]) # Same year label for panel 4 ax14.set_xticks(range(2002, 2019, 4)) ax14.set_xticklabels('') ax44.set_xticks(range(2002, 2019, 4)) ax44.set_xticklabels(range(2002, 2019, 4)) ax44.set_xlabel('Year') # Panel title ax11.set_title('Forest loss') ax12.set_title('Mean cloud impact') ax13.set_title('Cloud impact trend') ax14.set_title('Regional cloud impact') # # Add region names in column 4 # ax14.text(0.05,0.88,'Amazon' ,transform=ax14.transAxes) # ax24.text(0.05,0.55,'Indonesia' ,transform=ax24.transAxes) # ax34.text(0.2,0.1,'Southeast US' ,transform=ax34.transAxes) # ax44.text(0.05,0.05,'East Siberia' ,transform=ax44.transAxes) # Add region names on the left side of figure ax11.text(-0.21, 0.5, 'Amazon', transform=ax11.transAxes, rotation=90, va='center', fontsize=11) ax21.text(-0.21, 0.5, 'Indonesia', transform=ax21.transAxes, rotation=90, va='center', fontsize=11) ax31.text(-0.21, 0.5, 'Southeast US', transform=ax31.transAxes, rotation=90, va='center', fontsize=11) ax41.text(-0.21, 0.5, 'East Siberia', transform=ax41.transAxes, rotation=90, va='center', fontsize=11) # Add mean value on the panel floss_mean1 = loss.loss_effect.where( floss.forest_loss < -0.05).loc[-20:0, -70:-40].mean().values floss_mean2 = loss.loss_effect.where( floss.forest_loss < -0.05).loc[-5:15, 95:125].mean().values floss_mean3 = loss.loss_effect.where( floss.forest_loss < -0.05).loc[25:40, -95:-72.5].mean().values floss_mean4 = loss.loss_effect.where( floss.forest_loss < -0.05).loc[55:70, 115:137.5].mean().values # floss_mean1 = 100*trend.loss_impact.where(floss.forest_loss<-0.05).loc[-20:0,-70:-40].mean().values # floss_mean2 = 100*trend.loss_impact.where(floss.forest_loss<-0.05).loc[-5:15,95:125].mean().values # floss_mean3 = 100*trend.loss_impact.where(floss.forest_loss<-0.05).loc[25:40,-95:-72.5].mean().values # floss_mean4 = 100*trend.loss_impact.where(floss.forest_loss<-0.05).loc[55:70,115:137.5].mean().values ax12.text(0.04, 0.88, np.round(floss_mean1, 3), transform=ax12.transAxes, color='k') ax22.text(0.3, 0.55, np.round(floss_mean2, 3), transform=ax22.transAxes, color='k') ax32.text(0.04, 0.1, np.round(floss_mean3, 3), transform=ax32.transAxes, color='k') ax42.text(0.55, 0.88, np.round(floss_mean4, 3), transform=ax42.transAxes, color='k') # [plot_region_label(i, 'Amazon', 0.04,0.88) for i in [ax11, ax12, ax13]] # [plot_region_label(i, 'Indonesia', 0.3,0.55) for i in [ax21, ax22, ax23]] # [plot_region_label(i, 'Southeast US', 0.04,0.1) for i in [ax31, ax32, ax33]] # [plot_region_label(i, 'East Siberia', 0.55,0.88) for i in [ax41, ax42, ax43]] # move 2 and 3 column left to make space for 4 for i in [ax12, ax22, ax32, ax42]: move_left(i, offset=0.005) for i in [ax13, ax23, ax33, ax43]: move_left(i, offset=0.01) # Colorbar for regional plot cbar41_pos = [ ax41.get_position().x0, ax41.get_position().y0 - 0.035, ax41.get_position().width, 0.01 ] cax41 = fig.add_axes(cbar41_pos) cmap0, norm = norm_cmap(cmap='hot', vmin=-0.8, vmax=0) cb41 = mpl.colorbar.ColorbarBase( ax=cax41, cmap=cmap0.cmap, norm=norm, orientation='horizontal', ticks=np.arange(-0.8, 0, 0.2)) #cmap=plt.get_cmap('hot') cb41.ax.set_yticklabels(np.arange(-0.8, 0.1, 0.2), fontsize=10) cb41.set_label('Forest loss fraction', fontsize=12) cbar42_pos = [ ax42.get_position().x0, ax42.get_position().y0 - 0.035, ax42.get_position().width, 0.01 ] cax42 = fig.add_axes(cbar42_pos) cb42 = mpl.colorbar.ColorbarBase( ax=cax42, cmap=mycmap, norm=Normalize(vmin=-0.25, vmax=0.25), orientation='horizontal', ticks=np.arange(-0.2, 0.21, 0.1)) #cmap=plt.get_cmap('hot') cb42.set_label('$\Delta\mathrm{Cloud_{loss}}$', fontsize=12) cbar43_pos = [ ax43.get_position().x0, ax43.get_position().y0 - 0.035, ax43.get_position().width, 0.01 ] cax43 = fig.add_axes(cbar43_pos) cb43 = mpl.colorbar.ColorbarBase( ax=cax43, cmap=mycmap, norm=Normalize(vmin=-0.015, vmax=0.015), orientation='horizontal', ticks=np.arange(-0.015, 0.016, 0.005)) #cmap=plt.get_cmap('hot') cb43.set_ticklabels(np.arange(-1.5, 1.6, 0.5)) cb43.set_label('$\Delta \mathrm{Cloud_{loss}Trend}$ \n' + r'($\times$100/Year)', fontsize=12, ha='center') # Panel labels panel_txt = [chr(i) for i in range(ord('a'), ord('r') + 1)] ax_list = [ axbig1, axbig2, ax11, ax12, ax13, ax14, ax21, ax22, ax23, ax24, ax31, ax32, ax33, ax34, ax41, ax42, ax43, ax44 ] for i, a in enumerate(ax_list): if i > 1: plot_subplot_label(a, panel_txt[i], -0.1) else: plot_subplot_label(a, panel_txt[i]) plt.savefig('../figure/figure_floss0207.png', dpi=300, bbox_inches='tight') # plt.savefig('../figure/figure_floss.pdf',bbox_inches='tight') print('Figure saved')
if __name__ == '__main__': # set up real-time plot import matplotlib.pyplot as plt from matplotlib.cm import ScalarMappable from matplotlib.colors import Normalize fig1 = plt.figure(figsize=(8., 8.)) fig1.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) # fig1, (ax,pic) = plt.subplots(1,2) ax = fig1.gca() ax.set_xlim([-50,50]) ax.set_ylim([-50,50]) plt.margins(0,0) # note - points from up view, rectangle implies right view mycar = ax.add_patch(plt.Rectangle((-3.6,-1),5.,2.,0.,fill=True, color='k')) scatterpoints = ax.scatter([], [], 2., color=[], cmap = ScalarMappable(Normalize(0,7))) fig1.canvas.draw() plt.show(block=False) # fig1.canvas.update() fig1.canvas.flush_events() rotation_period = 1 # optionally don't update plot every time rotations = 0 with LIDAR() as lidar: while True: data = lidar.get(timeout=.11) # update plot rotations += 1 if rotations % rotation_period == 0: # thistime = time.time()
def drawGeoms(geoms, srs=4326, ax=None, simplificationFactor=5000, colorBy=None, figsize=(12, 12), xlim=None, ylim=None, fontsize=16, hideAxis=False, cbarPadding=0.01, cbarTitle=None, vmin=None, vmax=None, cmap="viridis", cbax=None, cbargs=None, leftMargin=0.01, rightMargin=0.01, topMargin=0.01, bottomMargin=0.01, **mplArgs): """Draw geometries onto a matplotlib figure * Each geometry type is displayed as an appropriate plotting type -> Points/ Multipoints are displayed as points using plt.plot(...) -> Lines/ MultiLines are displayed as lines using plt.plot(...) -> Polygons/ MultiPolygons are displayed as patches using the descartes library * Each geometry can be given its own set of matplotlib plotting parameters Notes: ------ This function does not call plt.show() for the final display of the figure. This must be done manually after calling this function. Otherwise plt.savefig(...) can be called to save the output somewhere. Sometimes geometries will disappear because of the simplification procedure. If this happens, the procedure can be avoided by setting simplificationFactor to None. This will take much more memory and will take longer to plot, however Parameters: ----------- geoms : ogr.Geometry or [ogr.Geometry, ] or pd.DataFrame The geometries to be drawn * If a DataFrame is given, the function looks for geometries under a columns named 'geom' * plotting arguments can be given by adding a column named 'MPL:****' where '****' stands in for the argument to be added - For geometries that should ignore this argument, set it as None srs : Anything acceptable to geokit.srs.loadSRS(); optional The srs in which to draw each geometry * If not given, longitude/latitude is assumed * Although geometries can be given in any SRS, it is very helpful if they are already provided in the correct SRS ax : matplotlib axis; optional The axis to draw the geometries on * If not given, a new axis is generated and returned simplificationFactor : float; optional The level to which geometries should be simplified. It can be thought of as the number of verticies allowed in either the X or Y dimension across the figure * A higher value means a more detailed plot, but may take longer to draw colorBy : str; optional The column in the geoms DataFrame to color by * Only useful when geoms is given as a DataFrame figsize : (int, int); optional The figure size to create when generating a new axis * If resultign figure looks wierd, altering the figure size is your best bet to make it look nicer xlim : (float, float); optional The x-axis limits ylim : (float, float); optional The y-axis limits fontsize : int; optional A base font size to apply to tick marks which appear * Titles and labels are given a size of 'fontsize' + 2 hideAxis : bool; optional Instructs the created axis to hide its boundary * Only useful when generating a new axis cbarPadding : float; optional The spacing padding to add between the generated axis and the generated colorbar axis * Only useful when generating a new axis * Only useful when 'colorBy' is given cbarTitle : str; optional The title to give to the generated colorbar * If not given, but 'colorBy' is given, the same string for 'colorBy' is used * Only useful when 'colorBy' is given vmin : float; optional The minimum value to color * Only useful when 'colorBy' is given vmax : float; optional The maximum value to color * Only useful when 'colorBy' is given cmap : str or matplotlib ColorMap; optional The colormap to use when coloring * Only useful when 'colorBy' is given cbax : matplotlib axis; optional An explicitly given axis to use for drawing the colorbar * If not given, but 'colorBy' is given, an axis for the colorbar is automatically generated cbargs : dict; optional keyword arguments to pass on when creating the colorbar leftMargin : float; optional Additional margin to add to the left of the figure * Before using this, try adjusting the 'figsize' rightMargin : float; optional Additional margin to add to the left of the figure * Before using this, try adjusting the 'figsize' topMargin : float; optional Additional margin to add to the left of the figure * Before using this, try adjusting the 'figsize' bottomMargin : float; optional Additional margin to add to the left of the figure * Before using this, try adjusting the 'figsize' **mplArgs All other keyword arguments are passed on to the plotting functions called for each geometry * Will be applied to ALL geometries. Be careful since this can cause errors when plotting geometries of different types Returns: -------- A namedtuple containing: 'ax' -> The map axis 'handles' -> All geometry handles which were created in the order they were drawn 'cbar' -> The colorbar handle if it was drawn """ if isinstance(ax, AxHands): ax = ax.ax if ax is None: newAxis = True import matplotlib.pyplot as plt plt.figure(figsize=figsize) if colorBy is None: # We don't need a colorbar if not hideAxis: leftMargin += 0.07 ax = plt.axes([ leftMargin, bottomMargin, 1 - (rightMargin + leftMargin), 1 - (topMargin + bottomMargin) ]) cbax = None else: # We need a colorbar rightMargin += 0.08 # Add area on the right for colorbar text if not hideAxis: leftMargin += 0.07 cbarExtraPad = 0.05 cbarWidth = 0.04 ax = plt.axes([ leftMargin, bottomMargin, 1 - (rightMargin + leftMargin + cbarWidth + cbarPadding), 1 - (topMargin + bottomMargin) ]) cbax = plt.axes([ 1 - (rightMargin + cbarWidth), bottomMargin + cbarExtraPad, cbarWidth, 1 - (topMargin + bottomMargin + 2 * cbarExtraPad) ]) if hideAxis: ax.axis("off") else: ax.tick_params(labelsize=fontsize) else: newAxis = False # Be sure we have a list pargs = None isFrame = False if isinstance(geoms, ogr.Geometry): geoms = [ geoms, ] elif isinstance( geoms, pd.DataFrame): # We have a DataFrame with plotting arguments isFrame = True data = geoms.drop("geom", axis=1) geoms = geoms["geom"].values pargs = pd.DataFrame(index=data.index) for c in data.columns: if not c[:4] == "MPL:": continue pargs[c[4:]] = data[c] if pargs.size == 0: pargs = None else: #Assume its an iterable geoms = list(geoms) # Check Geometry SRS if not srs is None: srs = loadSRS(srs) for gi, g in enumerate(geoms): gsrs = g.GetSpatialReference() if gsrs is None: continue # Skip it if we don't know it... if not gsrs.IsSame(srs): geoms[gi] = transform(geoms[gi], srs) # Apply simplifications if required if not simplificationFactor is None: if xlim is None or ylim is None: xMin, yMin, xMax, yMax = 1e100, 1e100, -1e100, -1e100 for g in geoms: _xMin, _xMax, _yMin, _yMax = g.GetEnvelope() xMin = min(_xMin, xMin) xMax = max(_xMax, xMax) yMin = min(_yMin, yMin) yMax = max(_yMax, yMax) if not xlim is None: xMin, xMax = xlim if not ylim is None: yMin, yMax = ylim simplificationValue = max(xMax - xMin, yMax - yMin) / simplificationFactor oGeoms = geoms geoms = [] def doSimplify(g): ng = g.Simplify(simplificationValue) return ng for g in oGeoms: #carefulSimplification=False #if carefulSimplification and "MULTI" in g.GetGeometryName(): if False and "MULTI" in g.GetGeometryName( ): # This doesn't seem to help... subgeoms = [] for gi in range(g.GetGeometryCount()): ng = doSimplify(g.GetGeometryRef(gi)) subgeoms.append(ng) geoms.append(flatten(subgeoms)) else: geoms.append(doSimplify(g)) ### Handle color value if not colorBy is None: colorVals = data[colorBy].values if isinstance(cmap, str): from matplotlib import cm cmap = getattr(cm, cmap) cValMax = colorVals.max() if vmax is None else vmax cValMin = colorVals.min() if vmin is None else vmin _colorVals = [ cmap(v) for v in (colorVals - cValMin) / (cValMax - cValMin) ] ### Do Plotting # make patches h = [] for gi, g in enumerate(geoms): if not pargs is None: s = [not v is None for v in pargs.iloc[gi]] plotargs = pargs.iloc[gi, s].to_dict() else: plotargs = dict() plotargs.update(mplArgs) if not colorBy is None: colorVal = _colorVals[gi] else: colorVal = None # Determine type if g.GetGeometryName() == "POINT": h.append(drawPoint(g, plotargs, ax, colorVal)) elif g.GetGeometryName() == "MULTIPOINT": h.append(drawMultiPoint(g, plotargs, ax, colorVal)) elif g.GetGeometryName() == "LINESTRING": h.append(drawLine(g, plotargs, ax, colorVal)) elif g.GetGeometryName() == "MULTILINESTRING": h.append(drawMultiLine(g, plotargs, ax, colorVal)) elif g.GetGeometryName() == "LINEARRING": h.append(drawLinearRing(g, plotargs, ax, colorVal)) elif g.GetGeometryName() == "POLYGON": h.append(drawPolygon(g, plotargs, ax, colorVal)) elif g.GetGeometryName() == "MULTIPOLYGON": h.append(drawMultiPolygon(g, plotargs, ax, colorVal)) else: msg = "Could not draw geometry of type:", pargs.index[ gi], "->", g.GetGeometryName() warnings.warn(msg, UserWarning) # Add the colorbar, maybe if not colorBy is None: from matplotlib.colorbar import ColorbarBase from matplotlib.colors import Normalize norm = Normalize(vmin=cValMin, vmax=cValMax) tmp = dict(cmap=cmap, norm=norm, orientation='vertical') if not cbargs is None: tmp.update(cbargs) cbar = ColorbarBase(cbax, **tmp) cbar.ax.tick_params(labelsize=fontsize) cbar.set_label(colorBy if cbarTitle is None else cbarTitle, fontsize=fontsize + 2) else: cbar = None # Do some formatting if newAxis: ax.set_aspect('equal') ax.autoscale(enable=True) if not xlim is None: ax.set_xlim(*xlim) if not ylim is None: ax.set_ylim(*ylim) # Organize return if isFrame: return AxHands(ax, pd.Series(h, index=data.index), cbar) else: return AxHands(ax, h, cbar)
def plot(self, data_group, fmt='', xmin=None, xmax=None, ymin=None, ymax=None, vmin=None, vmax=None, **kwargs): """Plot the NXdata group. Parameters ---------- data_group : NXdata NeXus group containing the data to be plotted. fmt : str, optional Formatting options that are compliant with PyPlot, by default '' xmin : float, optional Minimum x-boundary, by default None xmax : float, optional Maximum x-boundary, by default None ymin : float, optional Minimum y-boundary, by default None ymax : float, optional Maximum y-boundary, by default None vmin : float, optional Minimum signal value for 2D plots, by default None vmax : float, optional Maximum signal value for 2D plots, by default None **kwargs : dict Options used to customize the plot. """ try: import matplotlib.pyplot as plt except ImportError: raise NeXusError( "Default plotting package (matplotlib) not available.") over = kwargs.pop("over", False) image = kwargs.pop("image", False) log = kwargs.pop("log", False) logx = kwargs.pop("logx", False) logy = kwargs.pop("logy", False) signal = data_group.nxsignal if signal.ndim > 2 and not image: raise NeXusError( "Can only plot 1D and 2D data - please select a slice") elif signal.ndim > 1 and over: raise NeXusError("Cannot overplot 2D data") errors = data_group.nxerrors title = data_group.nxtitle # Provide a new view of the data if there is a dimension of length 1 data, axes = (signal.nxdata.reshape(data_group.plot_shape), data_group.plot_axes) isinteractive = plt.isinteractive() plt.ioff() try: if over: plt.autoscale(enable=False) else: plt.autoscale(enable=True) plt.clf() #One-dimensional Plot if len(data.shape) == 1: if fmt == '': fmt = 'o' if hasattr(signal, 'units'): if not errors and signal.units == 'counts': errors = NXfield(np.sqrt(data)) if errors: ebars = errors.nxdata plt.errorbar(centers(axes[0], data.shape[0]), data, ebars, fmt=fmt, **kwargs) else: plt.plot(centers(axes[0], data.shape[0]), data, fmt, **kwargs) if not over: ax = plt.gca() xlo, xhi = ax.set_xlim(auto=True) ylo, yhi = ax.set_ylim(auto=True) if xmin: xlo = xmin if xmax: xhi = xmax ax.set_xlim(xlo, xhi) if ymin: ylo = ymin if ymax: yhi = ymax ax.set_ylim(ylo, yhi) if logx: ax.set_xscale('symlog') if log or logy: ax.set_yscale('symlog') plt.xlabel(label(axes[0])) plt.ylabel(label(signal)) plt.title(title) #Two dimensional plot else: from matplotlib.colors import LogNorm, Normalize if image: x = boundaries(axes[-2], data.shape[-2]) y = boundaries(axes[-3], data.shape[-3]) xlabel, ylabel = label(axes[-2]), label(axes[-3]) else: x = boundaries(axes[-1], data.shape[-1]) y = boundaries(axes[-2], data.shape[-2]) xlabel, ylabel = label(axes[-1]), label(axes[-2]) if not vmin: vmin = np.nanmin(data[data > -np.inf]) if not vmax: vmax = np.nanmax(data[data < np.inf]) if not image: if log: vmin = max(vmin, 0.01) vmax = max(vmax, 0.01) kwargs["norm"] = LogNorm(vmin, vmax) else: kwargs["norm"] = Normalize(vmin, vmax) ax = plt.gca() if image: im = ax.imshow(data, **kwargs) ax.set_aspect('equal') else: im = ax.pcolormesh(x, y, data, **kwargs) im.get_cmap().set_bad('k', 1.0) ax.set_xlim(x[0], x[-1]) ax.set_ylim(y[0], y[-1]) ax.set_aspect('auto') if not image: plt.colorbar(im) if 'origin' in kwargs and kwargs['origin'] == 'lower': image = False if xmin: ax.set_xlim(left=xmin) if xmax: ax.set_xlim(right=xmax) if ymin: if image: ax.set_ylim(top=ymin) else: ax.set_ylim(bottom=ymin) if ymax: if image: ax.set_ylim(bottom=ymax) else: ax.set_ylim(top=ymax) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) if isinteractive: plt.pause(0.001) plt.show(block=False) else: plt.show() finally: if isinteractive: plt.ion()
def plot(self, **kwargs): r""" Display the selected content of the :attr:`~nenupy.astro.sky.Sky.value` attribute belonging to a :class:`~nenupy.astro.sky.Sky` instance as a celestial map in equatorial coordinates. This method is available on a :class:`~nenupy.astro.sky.SkySlice` instance, resulting from a selection upon a :class:`~nenupy.astro.sky.Sky` instance (using the indexing operator). Several parameters, listed below, can be tuned to adapt the plot to the user requirements: .. rubric:: Data display keywords :param center: Coordinates of the celestial map to be displayed at the center of the image. Default is ``(RA=0deg, Dec=0deg)``. :type center: :class:`~astropy.coordinates.SkyCoord` :param radius: Angular radius from the center of the image above which the plot should be cropped. Default is ``None`` (i.e., full sky image). :type radius: :class:`~astropy.units.Quantity` :param resolution: Set the pixel resolution. The upper threshold is 0.775 deg, any value above that does not affect the figure appearence. Default is ``astropy.units.Quantity(1, unit="deg")``. :type resolution: :class:`~astropy.units.Quantity` :param only_visible: If set to ``True`` only the sky above the horizon is displayed. Setting this parameter to ``False`` does not really make sense for :class:`~nenupy.astro.sky.Sky` instances representing antenna response for instance. Default is ``True``. :type only_visible: `bool` :param decibel: If set to ``True``, the data values are displayed at the decibel scale, i.e., :math:`10 \log( \rm{data} )`. Default is ``False``. :type decibel: `bool` .. rubric:: Overplot keywords :param scatter: Add a scatter plot (as defined in `matplotlib.pyplot.scatter`). Expected syntax is ``(<SkyCoord>, <marker_size>, <color>)``. Default is ``None`` (i.e., no scatter overplot). :type scatter: `tuple` :param text: Add a text overlay (as defined in `matplotlib.pyplot.text`). Expected syntax is ``(<SkyCoord>, <[text]>, <color>)``. Default is ``None`` (i.e., no text overplot). :type text: `tuple` :param contour: Add a contour plot (as defined in `matplotlib.pyplot.contour`). Expected syntax is ``(<numpy.ndarray>, <[levels]>, <colormap>)``. Default is ``None`` (i.e., no contour overplot). :type contour: `tuple` .. rubric:: Plotting layout keywords :param altaz_overlay: If set to ``True``, the horizontal coordinates grid is overplotted in addition to the equatorial one. Default is ``False``. :type altaz_overlay: `bool` :param cmap: Color map applied while representing the data (see `Matplotlib colormaps <https://matplotlib.org/stable/gallery/color/colormap_reference.html>`_). Default is ``"YlGnBu_r"``. :type cmap: `str` :param show_colorbar: Show or not the color bar. Default is ``True``. :type show_colorbar: `bool` :param colorbar_label: Set the label of the color bar. Default is ``""``. :type colorbar_label: `str` :param figname: Name of the file (absolute or relative path) to save the figure. If set to ``"return"``, the method returns the `tuple` ``(fig, ax)`` (as defined by `matplotlib <https://matplotlib.org/>`_). Default is ``None`` (i.e., only show the figure). :type figname: `str` :param figsize: Set the figure size. Default is ``(15, 10)``. :type figsize: `tuple` :param ticks_color: Set the color of the equatorial grid and the Right Ascension ticks. Default is ``"0.9"`` (grey). :type ticks_color: `str` :param title: Set the figure title. Default is ``"<time>, <frequency>"``. :type title: `str` """ # Parsing the keyword arguments resolution = kwargs.get("resolution", 1*u.deg) figname = kwargs.get("figname", None) cmap = kwargs.get("cmap", "YlGnBu_r") figsize = kwargs.get("figsize", (15, 10)) center = kwargs.get("center", SkyCoord(0*u.deg, 0*u.deg)) radius = kwargs.get("radius", None) ticks_color = kwargs.get("ticks_color", "0.9") colorbar_label = kwargs.get("colorbar_label", "") title = kwargs.get("title", f"{self.time.isot.split('.')[0]}, {self.frequency:.2f}") visible_sky = kwargs.get("only_visible", True) decibel = kwargs.get("decibel", False) altaz_overlay = kwargs.get("altaz_overlay", False) # Initialize figure wcs, shape = self._compute_wcs( center=center, resolution=getattr(self, "resolution", resolution), radius=radius ) fig = plt.figure(figsize=figsize) ax = plt.subplot( projection=wcs, frame_class=EllipticalFrame ) # Get the data projected on fullsky data = self._fullsky_projection( wcs=wcs, shape=shape, display_visible_sky=visible_sky ) # Scale the data in decibel if decibel: data = 10 * np.log10(data) vmin = kwargs.get("vmin", np.nanmin(data)) vmax = kwargs.get("vmax", np.nanmax(data)) # Plot the data im = ax.imshow( data, origin="lower", interpolation="quadric", cmap=cmap, vmin=vmin, vmax=vmax ) # Define ax ticks ax.coords.grid(color=ticks_color, alpha=0.5) path_effects=[patheffects.withStroke(linewidth=3, foreground='black')] ra_axis = ax.coords[0] dec_axis = ax.coords[1] ra_axis.set_ticks_visible(False) ra_axis.set_ticklabel_visible(True) ra_axis.set_ticklabel(color=ticks_color, exclude_overlapping=True, path_effects=path_effects) ra_axis.set_axislabel("RA", color=ticks_color, path_effects=path_effects) ra_axis.set_major_formatter("d") ra_axis.set_ticks(number=12) dec_axis.set_ticks_visible(False) dec_axis.set_ticklabel_visible(True) dec_axis.set_axislabel("Dec", minpad=2) dec_axis.set_major_formatter("d") dec_axis.set_ticks(number=10) if altaz_overlay: frame = AltAz(obstime=self.time, location=self.observer) overlay = ax.get_coords_overlay(frame) overlay.grid(color="tab:orange", alpha=0.5) az_axis = overlay[0] alt_axis = overlay[1] az_axis.set_axislabel("Azimuth", color=ticks_color, path_effects=path_effects) az_axis.set_ticks_visible(False) az_axis.set_ticklabel_visible(True) az_axis.set_ticklabel(color=ticks_color, path_effects=path_effects) az_axis.set_major_formatter("d") az_axis.set_ticks(number=12) alt_axis.set_axislabel("Elevation") alt_axis.set_ticks_visible(False) alt_axis.set_ticklabel_visible(True) alt_axis.set_major_formatter("d") alt_axis.set_ticks(number=10) # Add NSEW points nesw_labels = np.array(["N", "E", "S", "W"]) nesw = SkyCoord( np.array([0, 90, 180, 270]), np.array([0, 0, 0, 0]), unit="deg", frame=frame ).transform_to(ICRS) for label, coord in zip(nesw_labels, nesw): ax.text( x=coord.ra.deg, y=coord.dec.deg, s=label, color="tab:orange", transform=ax.get_transform("world"), path_effects=path_effects, verticalalignment="center", horizontalalignment="center", clip_on=True ) # Colorbar if kwargs.get("show_colorbar", True): cax = inset_axes( ax, width='3%', height='100%', loc='lower left', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0, ) cb = ColorbarBase( cax, cmap=get_cmap(name=cmap), orientation='vertical', norm=Normalize( vmin=vmin, vmax=vmax ), ticks=LinearLocator() ) cb.solids.set_edgecolor("face") cb.set_label(colorbar_label) cb.formatter.set_powerlimits((0, 0)) # Overplot # if kwargs.get("circle", None) is not None: # from matplotlib.patches import Circle # frame = AltAz(obstime=self.time, location=self.observer) # c = Circle( # (0, 75), # 20, # edgecolor='yellow', # linewidth=5, # facecolor='none', # #transform=ax.get_transform('world') # #transform=ax.get_transform('fk5') # transform=ax.get_transform(frame) # ) # ax.add_patch(c) if kwargs.get("moc", None) is not None: # In order fo that to work; I had to comment #axis_viewport.set(ax, wcs) # from add_patches_to_mpl_axe() in mocpy/moc/plot/fill.py # OR re-set the limits (done here) try: frame = AltAz(obstime=self.time, location=self.observer) xlimits = ax.get_xlim() ylimits = ax.get_ylim() mocs = kwargs["moc"] if isinstance(kwargs["moc"], list) else [kwargs["moc"]] for moc, color in zip(mocs, ["tab:red", "tab:green"]): moc.fill( ax=ax, wcs=wcs, alpha=0.5, fill=True, color=color, linewidth=0, ) ax.set_xlim(xlimits) ax.set_ylim(ylimits) except AttributeError: log.warning("A 'MOC' object, generated from mocpy is expected.") raise if kwargs.get("altaz_moc", None) is not None: xlimits = ax.get_xlim() ylimits = ax.get_ylim() altaz = self.horizontal_coordinates mask = kwargs["altaz_moc"].contains(altaz.az, altaz.alt) ax.scatter( x=self.coordinates[mask].ra.deg, y=self.coordinates[mask].dec.deg, s=0.1,#[marker_size]*coords.size, facecolor="red", edgecolor=None, alpha=0.5, transform=ax.get_transform("world") ) ax.set_xlim(xlimits) ax.set_ylim(ylimits) if kwargs.get("scatter", None) is not None: parameters = kwargs["scatter"] if len(parameters) != 3: raise ValueError( "'scatter' syntax should be: (<SkyCoord>, <size>, <color>)" ) coords = parameters[0] if coords.isscalar: coords = coords.reshape((1,)) marker_size = parameters[1] marker_color = parameters[2] ax.scatter( x=coords.ra.deg, y=coords.dec.deg, s=[marker_size]*coords.size, color=marker_color, transform=ax.get_transform("world") ) if kwargs.get("text", None) is not None: parameters = kwargs["text"] if len(parameters) != 3: raise ValueError( "'text' syntax should be: (<SkyCoord>, <[text]>, <color>)" ) coords = parameters[0] if coords.isscalar: coords = coords.reshape((1,)) text = parameters[1] text_color = parameters[2] for i in range(coords.size): ax.text( x=coords[i].ra.deg, y=coords[i].dec.deg, s=text[i], color=text_color, transform=ax.get_transform("world"), clip_on=True ) if kwargs.get("contour", None) is not None: parameters = kwargs["contour"] data = parameters[0] if len(parameters) != 3: raise ValueError( "'contour' syntax should be: (<numpy.ndarray>, <[levels]>, <colormap>)" ) contour, _ = reproject_from_healpix( (data, ICRS()), wcs, nested=False, shape_out=shape#(ndec, nra) ) ax.contour( contour, levels=parameters[1], cmap=parameters[2], ) # Other im.set_clip_path(ax.coords.frame.patch) ax.set_title(title, pad=20) # Save or show if figname is None: plt.show() elif figname.lower() == "return": return fig, ax else: fig.savefig( figname, dpi=300, transparent=True, bbox_inches='tight' ) plt.close('all')
def detector_plot_dict(params, detector, data, title, units_str, show=True, reverse_colormap=False): """ Use matplotlib to plot a detector, color coding panels according to data @param detector detector reference detector object @param data python dictionary of panel names as keys and numbers as values @param title title string for plot @param units_str string with a formatting statment for units on each panel """ # initialize the color map values = flex.double(data.values()) norm = Normalize(vmin=flex.min(values), vmax=flex.max(values)) if reverse_colormap: cmap = plt.cm.get_cmap(params.colormap + "_r") else: cmap = plt.cm.get_cmap(params.colormap) sm = cm.ScalarMappable(norm=norm, cmap=cmap) if len(values) == 0: print "no values" return elif len(values) == 1: sm.set_array(np.arange(values[0], values[0], 1)) # needed for colorbar else: sm.set_array(np.arange(flex.min(values), flex.max(values), (flex.max(values)-flex.min(values))/20)) # needed for colorbar fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') max_dim = 0 root = detector.hierarchy() rf = col(root.get_fast_axis()) rs = col(root.get_slow_axis()) for pg_id, pg in enumerate(iterate_detector_at_level(root, 0, params.hierarchy_level)): if pg.get_name() not in data: continue # get panel coordinates p0, p1, p2, p3 = get_bounds(root, pg) v1 = p1-p0 v2 = p3-p0 vcen = ((v2/2) + (v1/2)) + p0 # add the panel to the plot ax.add_patch(Polygon((p0[0:2],p1[0:2],p2[0:2],p3[0:2]), closed=True, color=sm.to_rgba(data[pg.get_name()]), fill=True)) ax.annotate("%d %s"%(pg_id, units_str%data[pg.get_name()]), vcen[0:2], ha='center') if params.draw_normal_arrows: pgn = col(pg.get_normal()) v = col((rf.dot(pgn), rs.dot(pgn), 0)) v *= 10000 ax.arrow(vcen[0], vcen[1], v[0], v[1], head_width=5.0, head_length=10.0, fc='k', ec='k') # find the plot maximum dimensions for p in [p0, p1, p2, p3]: for c in p[0:2]: if abs(c) > max_dim: max_dim = abs(c) # plot the results ax.set_xlim((-max_dim,max_dim)) ax.set_ylim((-max_dim,max_dim)) ax.set_xlabel("mm") ax.set_ylabel("mm") fig.colorbar(sm) plt.title(title) if show: plt.show()
def spikesplot(ts_z, outer_gs=None, tr=None, zscored=True, spike_thresh=6., title='Spike plot', ax=None, cmap='viridis', hide_x=True, nskip=0): """ A spikes plot. Thanks to Bob Dogherty (this docstring needs be improved with proper ack) """ if ax is None: ax = plt.gca() if not outer_gs is None: gs = mgs.GridSpecFromSubplotSpec(1, 2, subplot_spec=outer_gs, width_ratios=[1, 100], wspace=0.0) ax = plt.subplot(gs[1]) # Define TR and number of frames if tr is None: tr = 1. # Load timeseries, zscored slice-wise nslices = ts_z.shape[0] ntsteps = ts_z.shape[1] # Load a colormap my_cmap = get_cmap(cmap) norm = Normalize(vmin=0, vmax=float(nslices - 1)) colors = [my_cmap(norm(sl)) for sl in range(nslices)] stem = len(np.unique(ts_z).tolist()) == 2 # Plot one line per axial slice timeseries for sl in range(nslices): if not stem: ax.plot(ts_z[sl, :], color=colors[sl], lw=0.5) else: markerline, stemlines, baseline = ax.stem(ts_z[sl, :]) plt.setp(markerline, 'markerfacecolor', colors[sl]) plt.setp(baseline, 'color', colors[sl], 'linewidth', 1) plt.setp(stemlines, 'color', colors[sl], 'linewidth', 1) # Handle X, Y axes ax.grid(False) # Handle X axis last = ntsteps - 1 ax.set_xlim(0, last) xticks = list(range(0, last)[::20]) + [last] if not hide_x else [] ax.set_xticks(xticks) if not hide_x: if tr is None: ax.set_xlabel('time (frame #)') else: ax.set_xlabel('time (s)') ax.set_xticklabels( ['%.02f' % t for t in (tr * np.array(xticks)).tolist()]) # Handle Y axis if zscored: ax.set_ylabel('z-score') zs_max = np.abs(ts_z).max() ax.set_ylim((-(np.abs(ts_z[:, nskip:]).max()) * 1.05, (np.abs(ts_z[:, nskip:]).max()) * 1.05)) ytick_vals = np.arange(0.0, zs_max, float(np.floor(zs_max / 2.))) yticks = list(reversed( (-1.0 * ytick_vals[ytick_vals > 0]).tolist())) + ytick_vals.tolist() # TODO plot min/max or mark spikes # yticks.insert(0, ts_z.min()) # yticks += [ts_z.max()] for val in ytick_vals: ax.plot((0, ntsteps - 1), (-val, -val), 'k:', alpha=.2) ax.plot((0, ntsteps - 1), (val, val), 'k:', alpha=.2) # Plot spike threshold if zs_max < spike_thresh: ax.plot((0, ntsteps - 1), (-spike_thresh, -spike_thresh), 'k:') ax.plot((0, ntsteps - 1), (spike_thresh, spike_thresh), 'k:') else: ax.set_ylabel('air sgn. intensity') yticks = [ ts_z[:, nskip:].min(), np.median(ts_z[:, nskip:]), ts_z[:, nskip:].max() ] ax.set_ylim(ts_z[:, nskip:].min() * 0.95, ts_z[:, nskip:].max() * 1.05) if yticks: ax.set_yticks(yticks) ax.set_yticklabels(['%.02f' % y for y in yticks]) # Plot maximum and minimum horizontal lines ax.plot((0, ntsteps - 1), (yticks[0], yticks[0]), 'k:') ax.plot((0, ntsteps - 1), (yticks[-1], yticks[-1]), 'k:') for side in ["top", "right"]: ax.spines[side].set_color('none') ax.spines[side].set_visible(False) if not hide_x: ax.spines["bottom"].set_position(('outward', 20)) ax.xaxis.set_ticks_position('bottom') else: ax.spines["bottom"].set_color('none') ax.spines["bottom"].set_visible(False) ax.spines["left"].set_position(('outward', 30)) ax.yaxis.set_ticks_position('left') # labels = [label for label in ax.yaxis.get_ticklabels()] # labels[0].set_weight('bold') # labels[-1].set_weight('bold') if title: ax.set_title(title) return ax
import matplotlib.cm as cm from matplotlib.colors import Normalize import datetime import dateutil import numpy as np import os import sys # Global settings ww = 14.0 # figure width wh = ww / 1.414286 # to fit A4 paper size h = 0.8 # height of rectangles cmap = cm.autumn # colormap norm = Normalize(vmin=0.5, vmax=10.01) # Priority normalization [1-10] now = datetime.datetime.now() def to_datetime(datetxt): """Text to the date""" if isinstance(datetxt, datetime.datetime): return datetxt try: date = dateutil.parser.parse(datetxt) return date except: print("Error: can not get date from the string: {}".format(datetxt)) return None
latdiff = int((north - south) * 1200) npix = 0 #(90-north)*4 spix = latdiff #(90-south)*4 wpix = 0 #(180+west)*4 epix = londiff #(180+east)*4 #cmap=make_colormap(colors_list) #cmap=mbar.colormap("H02") # cmap=cm.seismic # cmap=cm.rainbow_r # #cmap.set_under("w",alpha=0) # cmapL=cmap #cm.get_cmap("rainbow_r") vmin = 1.0 vmax = 26.0 norm = Normalize(vmin=vmin, vmax=vmax) bounds = np.arange(-0.5, 26, 1.0) #cmap=colors.ListedColormap(['grey',"xkcd:ultramarine",'xkcd:clear blue','xkcd:jungle green',"xkcd:shamrock","xkcd:electric green","xkcd:sunny yellow","xkcd:neon red","xkcd:black"]) #cmap=colors.ListedColormap(['grey','xkcd:jungle green',"xkcd:shamrock","xkcd:electric green","xkcd:ultramarine",'xkcd:clear blue',"xkcd:sunny yellow","xkcd:neon red","xkcd:black"]) #cmap=colors.ListedColormap(['grey','xkcd:jungle green',"xkcd:shamrock","xkcd:greeny blue","xkcd:ultramarine",'xkcd:clear blue',"xkcd:sunny yellow","xkcd:neon red","xkcd:black"]) # cmap=colors.ListedColormap(['grey',"xkcd:dark seafoam",'xkcd:deep teal',"xkcd:saffron","xkcd:purpleish",'xkcd:royal',"xkcd:peacock blue","xkcd:carmine","xkcd:black"]) ### # sea=0 # land(undefined)=1 # land(defined in CaMa)=2 # grid-box=3 # catchment-boundary=5 # channel=10 # outlet-pixel=20 # river-mouth=25
def plot_hextensor(tensor, image_range=(0, None), channel_range=(0, None), cmap=mymap, norm=None, linewidth=1, edgecolors='k', zorder=None, figname="figure", mask=[]): r"""Plot the hexagonal representation of a 4D tensor according to the addressing sheme used by HexagDLy. Args: tensor: torch tensor or numpy array containing the hexagonal data points image_range: tuple of ints, range defining the images to be plotted channel_range: tuple of ints, range defining the channels to be plotted cmap: colourmap figname: str, name of figure mask: list of ints that depict the pixels to skip in plots counting top to bottom left to right from the top left pixel """ try: tensor = tensor.data.numpy() except: pass if norm is None: norm = Normalize(tensor.min(), tensor.max()) if isinstance(edgecolors, np.ndarray) or isinstance(edgecolors, list): edgecolors[(edgecolors == '') | (edgecolors == '1')] = 'k' inshape = np.shape(tensor[image_range[0]:image_range[1], channel_range[0]:channel_range[1]]) inexamples = inshape[0] inchannels = inshape[1] if inexamples != 1 and inchannels != 1: print( "Choose one image and n channels or one channel an n images to display!" ) sys.exit() nimages = max(inexamples, inchannels) hexagons = [[] for i in range(nimages)] intensities = [[] for i in range(nimages)] fig = plt.figure(figname, (5, 5)) fig.clear() nrows = int(np.ceil(np.sqrt(nimages))) gs = gridspec.GridSpec(nrows, nrows) gs.update(wspace=0, hspace=0) for i in range(nimages): if inexamples >= inchannels: a = i b = 0 else: a = 0 b = i npixel = 0 for x in range( np.shape(tensor[image_range[0] + a, channel_range[0] + b])[1]): for y in range( np.shape(tensor[image_range[0] + a, channel_range[0] + b])[0]): if npixel not in mask: intensity = tensor[image_range[0] + a, channel_range[0] + b, y, x] hexagon = RegularPolygon( (x * np.sqrt(3) / 2, -(y + np.mod(x, 2) * 0.5)), 6, 0.577349, orientation=np.pi / 6, ) intensities[i].append(intensity) hexagons[i].append(hexagon) npixel += 1 ax = fig.add_subplot(gs[i]) ax.set_xlim([ -1, np.shape(tensor[image_range[0] + a, channel_range[0] + b])[1] ]) #embed() ax.set_ylim([ -1.15 * np.shape(tensor[image_range[0] + a, channel_range[0] + b])[0] - 1, 1, ]) ax.set_axis_off() p = PatchCollection(np.array(hexagons[i]), cmap=cmap, norm=norm, alpha=0.9, edgecolors="k", linewidth=linewidth) p.set_array(np.array(np.array(intensities[i]))) p.set_linewidth(linewidth) p.set_cmap(cmap) #p.set_norm(norm) p.set_edgecolors(edgecolors) p.set_zorder(zorder) ax.add_collection(p) ax.set_aspect("equal") plt.subplots_adjust(top=0.95, bottom=0.05) plt.tight_layout()
def compute_r2_score_colors(r2_dat_plot, del_r2_dat_plot, n_subjs, n_freqs, n_coefs, reg_r2_test_ave, r2_thresh): ''' Takes in R2 scores and delta R2 scores for each input feature and converts them to RGB colors based on color map defined in config file. ''' cmap = get_cmap(config.constants_regress['cmap_r2']) red_cm = { 'red': ((0, 1, 1), (1, 1, 1)), 'green': ((0, 1, 1), (1, 0, 0)), 'blue': ((0, 1, 1), (1, 0, 0)) } cdict = {**red_cm, "alpha": ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))} cmap_w = LinearSegmentedColormap("curr_cmap", cdict) norm = Normalize(vmin=config.constants_regress['vscale_r2'][0], vmax=config.constants_regress['vscale_r2'][1]) colors_all = np.empty([n_subjs, n_freqs, n_coefs], dtype=object) colors_all_r2 = np.empty([n_subjs, n_freqs], dtype=object) vals_all_r2imp = colors_all.copy() for i in range(n_subjs): tmp_val_lo = del_r2_dat_plot[i, :, :, 0] tmp_val_hi = del_r2_dat_plot[i, :, :, 1] reg_r2_test_lo = r2_dat_plot[i, :, 0] reg_r2_test_hi = r2_dat_plot[i, :, 1] for s in range(n_coefs): if s == 0: colors_lo, colors_hi = [], [] for test_val in reg_r2_test_lo.tolist(): if str(test_val) != 'nan': colors_lo.append(cmap(norm(test_val))[0:3]) for test_val in reg_r2_test_hi.tolist(): if str(test_val) != 'nan': colors_hi.append(cmap(norm(test_val))[0:3]) colors_all[i, 0, s] = colors_lo.copy() colors_all[i, 1, s] = colors_hi.copy() vals_all_r2imp[i, 0, s] = reg_r2_test_lo.tolist() vals_all_r2imp[i, 1, s] = reg_r2_test_hi.tolist() tmp_val_lo_r2 = reg_r2_test_ave[ i, :, 0].tolist() #test_full_all[i][::2] tmp_val_lo_r2 = [ val for val in tmp_val_lo_r2 if str(val) != 'nan' ] tmp_val_lo_r2 = [ val if val > r2_thresh else r2_thresh for val in tmp_val_lo_r2 ] tmp_val_hi_r2 = reg_r2_test_ave[ i, :, 1].tolist() #test_full_all[i][1::2] tmp_val_hi_r2 = [ val for val in tmp_val_hi_r2 if str(val) != 'nan' ] tmp_val_hi_r2 = [ val if val > r2_thresh else r2_thresh for val in tmp_val_hi_r2 ] colors_lo_w, colors_hi_w = [], [] for j in range(len(tmp_val_lo_r2)): colors_lo_w.append(cmap_w(norm(tmp_val_lo_r2[j]))[0:3]) for j in range(len(tmp_val_hi_r2)): colors_hi_w.append(cmap_w(norm(tmp_val_hi_r2[j]))[0:3]) colors_all_r2[i, 0] = colors_lo_w.copy() colors_all_r2[i, 1] = colors_hi_w.copy() else: colors_lo, colors_hi = [], [] vals_lo, vals_hi = [], [] for j in range(tmp_val_lo.shape[0]): if str(tmp_val_lo[j, s - 1]) != 'nan': colors_lo.append(cmap(norm(tmp_val_lo[j, s - 1]))[0:3]) vals_lo.append(tmp_val_lo[j, s - 1]) colors_all[i, 0, s] = colors_lo.copy() for j in range(tmp_val_hi.shape[0]): if str(tmp_val_hi[j, s - 1]) != 'nan': colors_hi.append(cmap(norm(tmp_val_hi[j, s - 1]))[0:3]) vals_hi.append(tmp_val_hi[j, s - 1]) colors_all[i, 1, s] = colors_hi.copy() vals_all_r2imp[i, 0, s] = vals_lo.copy() vals_all_r2imp[i, 1, s] = vals_hi.copy() return colors_all, colors_all_r2, vals_all_r2imp, cmap
maxsizeintra = np.max(np.array(all_aps)) figintra = plt.figure(200 + ii) axintra = figintra.add_subplot(111, sharex=axshare, sharey=axshare) str_mat_intra = np.dot( np.atleast_2d(np.ones(all_freqs.shape[1])).T, np.atleast_2d(np.array(strength_list))) scale_marker = 1.5 axintra.scatter( x=str_mat_intra.flatten(), y=(np.abs(np.array(all_freqs)).T.flatten() - q_frac) / Qs, s=np.clip( np.array(all_aps).T.flatten() / maxsizeintra * scale_marker, 0.0, scale_marker), #c=np.clip(np.array(all_aps).T.flatten()/maxsizeintra, 0.3, 0.4), cmap=cm.Blues, norm=Normalize(vmin=0, vmax=0.5), color='C0') if flag_mode_0: # Plot mode zero mask_plot_mode_0 = np.array(stre_mode_0) < insta_thresh axintra.plot( np.array(stre_mode_0)[mask_plot_mode_0], (np.array(freq_mode_0)[mask_plot_mode_0] - q_frac) / Qs, '.k') if flag_mode_unstab: # Plot unstable freq freq_instab, ap_instab, stre_instab = extract_independent_lines( strength_list, all_freqs, all_aps, 1e-3, np.ones_like(strength_list, dtype=np.int)) mask_instab = np.array(stre_instab) > insta_thresh axintra.plot(np.array(stre_instab)[mask_instab],
def draw_networkx_edges( G, pos, edgelist=None, width=1.0, edge_color="k", style="solid", alpha=None, arrowstyle="-|>", arrowsize=10, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, node_size=300, nodelist=None, node_shape="o", connectionstyle=None, min_source_margin=0, min_target_margin=0, ): """Draw the edges of the graph G. This draws only the edges of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color or array of colors (default='k') Edge color. Can be a single color or a sequence of colors with the same length as edgelist. Color can be string, or rgb (or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=None) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. Note: Arrows will be the same color as edges. arrowstyle : str, optional (default='-|>') For directed graphs, choose the style of the arrow heads. See :py:class: `matplotlib.patches.ArrowStyle` for more options. arrowsize : int, optional (default=10) For directed graphs, choose the size of the arrow head head's length and width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale` for more info. connectionstyle : str, optional (default=None) Pass the connectionstyle parameter to create curved arc of rounding radius rad. For example, connectionstyle='arc3,rad=0.2'. See :py:class: `matplotlib.patches.ConnectionStyle` and :py:class: `matplotlib.patches.FancyArrowPatch` for more info. label : [None| string] Label for legend min_source_margin : int, optional (default=0) The minimum margin (gap) at the begining of the edge at the source. min_target_margin : int, optional (default=0) The minimum margin (gap) at the end of the edge at the target. Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edges list of matplotlib.patches.FancyArrowPatch `FancyArrowPatch` instances of the directed edges Depending whether the drawing includes arrows or not. Notes ----- For directed graphs, arrows are drawn at the head end. Arrows can be turned off with keyword arrows=False. Be sure to include `node_size` as a keyword argument; arrows are drawn considering the size of nodes. Examples -------- >>> G = nx.dodecahedral_graph() >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)]) >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> alphas = [0.3, 0.4, 0.5] >>> for i, arc in enumerate(arcs): # change alpha values of arcs ... arc.set_alpha(alphas[i]) Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ import matplotlib.pyplot as plt from matplotlib.colors import colorConverter, Colormap, Normalize from matplotlib.collections import LineCollection from matplotlib.patches import FancyArrowPatch import numpy as np if ax is None: ax = plt.gca() if edgelist is None: edgelist = list(G.edges()) if len(edgelist) == 0: # no edges! if not G.is_directed() or not arrows: return LineCollection(None) else: return [] if nodelist is None: nodelist = list(G.nodes()) # FancyArrowPatch handles color=None different from LineCollection if edge_color is None: edge_color = "k" # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) # Check if edge_color is an array of floats and map to edge_cmap. # This is the only case handled differently from matplotlib if ( np.iterable(edge_color) and (len(edge_color) == len(edge_pos)) and np.alltrue([isinstance(c, Number) for c in edge_color]) ): if edge_cmap is not None: assert isinstance(edge_cmap, Colormap) else: edge_cmap = plt.get_cmap() if edge_vmin is None: edge_vmin = min(edge_color) if edge_vmax is None: edge_vmax = max(edge_color) color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax) edge_color = [edge_cmap(color_normal(e)) for e in edge_color] if not G.is_directed() or not arrows: edge_collection = LineCollection( edge_pos, colors=edge_color, linewidths=width, antialiaseds=(1,), linestyle=style, transOffset=ax.transData, alpha=alpha, ) edge_collection.set_cmap(edge_cmap) edge_collection.set_clim(edge_vmin, edge_vmax) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(label) ax.add_collection(edge_collection) return edge_collection arrow_collection = None if G.is_directed() and arrows: # Note: Waiting for someone to implement arrow to intersection with # marker. Meanwhile, this works well for polygons with more than 4 # sides and circle. def to_marker_edge(marker_size, marker): if marker in "s^>v<d": # `large` markers need extra space return np.sqrt(2 * marker_size) / 2 else: return np.sqrt(marker_size) / 2 # Draw arrows with `matplotlib.patches.FancyarrowPatch` arrow_collection = [] mutation_scale = arrowsize # scale factor of arrow head # FancyArrowPatch doesn't handle color strings arrow_colors = colorConverter.to_rgba_array(edge_color, alpha) for i, (src, dst) in enumerate(edge_pos): x1, y1 = src x2, y2 = dst shrink_source = 0 # space from source to tail shrink_target = 0 # space from head to target if np.iterable(node_size): # many node sizes source, target = edgelist[i][:2] source_node_size = node_size[nodelist.index(source)] target_node_size = node_size[nodelist.index(target)] shrink_source = to_marker_edge(source_node_size, node_shape) shrink_target = to_marker_edge(target_node_size, node_shape) else: shrink_source = shrink_target = to_marker_edge(node_size, node_shape) if shrink_source < min_source_margin: shrink_source = min_source_margin if shrink_target < min_target_margin: shrink_target = min_target_margin if len(arrow_colors) == len(edge_pos): arrow_color = arrow_colors[i] elif len(arrow_colors) == 1: arrow_color = arrow_colors[0] else: # Cycle through colors arrow_color = arrow_colors[i % len(arrow_colors)] if np.iterable(width): if len(width) == len(edge_pos): line_width = width[i] else: line_width = width[i % len(width)] else: line_width = width arrow = FancyArrowPatch( (x1, y1), (x2, y2), arrowstyle=arrowstyle, shrinkA=shrink_source, shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, connectionstyle=connectionstyle, linestyle=style, zorder=1, ) # arrows go behind nodes # There seems to be a bug in matplotlib to make collections of # FancyArrowPatch instances. Until fixed, the patches are added # individually to the axes instance. arrow_collection.append(arrow) ax.add_patch(arrow) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() ax.tick_params( axis="both", which="both", bottom=False, left=False, labelbottom=False, labelleft=False, ) return arrow_collection
import matplotlib.pyplot as plt import numpy as np import matplotlib.cm as cm from matplotlib.colors import Normalize dt = np.loadtxt( file ) x=dt[:,0] y=dt[:,1] vol=dt[:,3] w=dt[:,4] ux=dt[:,5] uy=dt[:,6] colors = w norm = Normalize() norm.autoscale(colors) colormap = cm.inferno plt.figure(figsize=(6, 6)) plt.quiver(x,y, ux, uy , color=colormap(norm(colors)) ,angles='xy', scale_units='xy', scale=10, pivot='mid' ) #plt.xlim(-.4,.4) #plt.ylim(-.4,.4) #plt.colorbar() plt.show()
def _make_contour(self, **kwargs): """ method for generalizanting contour and colorbar plotting kwargs cax = matplotlib.Axes used to print colorbar. Default use make_axes_locatable """ Z = self.data.copy() if self.kwargs['vlim'] is not None: vmin, vmax = self.kwargs['vlim'] else: vmin, vmax = [Z.min().min(), Z.max().max()] #np.nanpercentile(Z,[2.5,97.5]) # print vmin, vmax colorbarKwd = {'extend': 'both'} contourKwd = { 'cmap': self.colormap } #'levels':np.linspace(vmin,vmax,100), if self.kwargs['colorbarKind'] == 'Linear': contourKwd['norm'] = Normalize(vmin, vmax) elif self.kwargs['colorbarKind'] == 'Anomaly': contourKwd['norm'] = MidpointNormalize(midpoint=0., vmin=vmin, vmax=vmax) colorbarKwd['format'] = self.kwargs['format'] elif self.kwargs['colorbarKind'] == 'Log': Z.mask(Z <= 0, inplace=True) if self.kwargs['vlim'] is None: vmin, vmax = [Z.min().min(), Z.max().max()] # np.nanpercentile(Z,[1,99]))) # Z[Z < vmin] = vmin # Z[Z > vmax] = vmax contourKwd['norm'] = LogNorm(vmin, vmax) print vmin, vmax minorTicks = np.hstack( [np.arange(1, 10, 1) * log for log in np.logspace(-2, 16, 19)]) minorTicks = minorTicks[(minorTicks >= vmin) & (minorTicks <= vmax)] colorbarKwd.update( dict(format=LogFormatterMathtext(10), ticks=LogLocator(10))) args = (self.x, self.y, Z) cf = self.axes[0].pcolormesh(*args, **contourKwd) # cf = ax.contourf(X,Y,Z,**contourKwd) #extend='both') if 'cax' not in kwargs.keys(): divider = make_axes_locatable(self.axes[0]) cax = divider.append_axes("right", size="3%", pad='1%') else: cax = kwargs['cax'] cbar = plt.colorbar(cf, cax=cax, **colorbarKwd) cbar.set_label(self.kwargs['cbarLabel'], weight='bold') if self.kwargs['colorbarKind'] == 'Log': cbar.ax.yaxis.set_ticks(cf.norm(minorTicks), minor=True) cbar.ax.tick_params(which='minor', width=1, length=4) cbar.ax.tick_params(which='major', width=1, length=6) # ax.yaxis.set_minor_locator(LogLocator(10,subs=np.arange(2,10))) self.kwargs['colorbarKind'] = 'Linear' return cf, cbar
def _fcn(y, k, mask=mask): # Get a mask for data: if pltype is 'pcolor': im = plt.pcolormesh(xvec, yvec, y, cmap=cmap, vmin=vmin, vmax=vmax, **pltargs) elif pltype is 'imshow': if np.array(mask).size: mask = np.array(mask) norm = Normalize(vmin, vmax) y = plt.get_cmap(cmap)(norm(y)) y[..., 3] = mask[k, ...] # Plot picture: im = plt.imshow(y, aspect='auto', cmap=cmap, origin='upper', interpolation=interpolation, vmin=vmin, vmax=vmax, extent=[xvec[0], xvec[-1], yvec[-1], yvec[0]], **pltargs) plt.gca().invert_yaxis() elif pltype is 'contour': im = plt.contourf(xvec, yvec, y, ncontour, cmap=cmap, vmin=vmin, vmax=vmax, **pltargs) # Manage under and over: if (under is not None) and (isinstance(under, str)): im.cmap.set_under(color=under) if (over is not None) and (isinstance(over, str)): im.cmap.set_over(color=over) # Manage contour: if contour is not None: contour_bck = contour.copy() # Unpack necessary arguments : datac = contour_bck['data'] level = contour_bck['level'] # Check data size: if len(datac.shape) == 2: datac = datac[np.newaxis, ...] contour_bck.pop('data'), contour_bck.pop('level') _ = plt.contour(datac[k, ...], extent=[xvec[0], xvec[-1], yvec[0], yvec[-1]], levels=level, **contour_bck) # Manage ticks, labek etc: plt.axis('tight') ax = plt.gca() _pltutils(ax, kwout['title'][k], kwout['xlabel'][k], kwout['ylabel'][k], **kwargs) # Manage colorbar: if colorbar: cb = plt.colorbar(im, shrink=0.7, pad=0.01, aspect=10) if cbticks == 'auto': clim = im.colorbar.get_clim() cb.set_ticks([clim[0], (clim[0]+clim[1])/2, clim[1]]) elif cbticks == 'minmax': clim = im.colorbar.get_clim() cb.set_ticks([clim[0], clim[1]]) elif cbticks is None: pass else: cb.set_ticks(cbticks) cb.set_label(cblabel, labelpad=ycb) cb.outline.set_visible(False) # Text inside: if textin: for k in range(y.shape[0]): for i in range(y.shape[1]): plt.text(i + 0.5, k + 0.5, textype % y[i, k], color=textcolor, horizontalalignment='center', verticalalignment='center')
def main(): if len(sys.argv) < 4: sys.stderr.write( "USAGE: " + sys.argv[0] + " [path to simplified building data] [path to mappings] [road network]\n" ) sys.exit(1) buildings = load_buildings(sys.argv[1]) with open(sys.argv[3], 'r', encoding='utf-8') as file: network = RoadNetwork(file) with open(sys.argv[2], "r", encoding="utf-8") as f: reader = csv.reader(f) next(reader) mappings = {} for row in reader: vehicle = int(row[0]) bldg = int(row[4]) mapped_count = int(row[8]) buildings[bldg]["count"] = mapped_count mappings[vehicle] = { "building": bldg, "x": float(row[2]), "y": float(row[3]), "distance": float(row[7]) } counts = np.fromiter(filter(lambda x: x > 0, map(lambda b: b["count"], buildings.values())), float) if LOG_SCALING: counts = np.log(counts) cq1, cq3, cf1, cf2 = fences(counts) norm = Normalize(0, cf2, clip=True) # Set up figure and axes: fig = plt.figure() ax = fig.add_subplot(aspect="equal") plot_roads(ax, network, color_roads=False, plot_nodes=False, alpha=0.70, default_road_color='#FFFFFF') for bldg in buildings.values(): edge_alpha = 1.0 alpha = 0.8 if bldg["count"] <= 0: bldg["color"] = (0, 0, 0, 0) edge_alpha = 0.5 else: if LOG_SCALING: count = np.log(bldg["count"]) else: count = bldg["count"] bldg["color"] = HEAT_CM_1(norm(count), alpha=alpha) patch = bldg["poly"] patch.set_edgecolor((0, 0, 0, edge_alpha)) patch.set_facecolor(bldg["color"]) patch.set_fill(True) ax.add_patch(patch) vids = np.fromiter(mappings.keys(), int, len(mappings)) n = min(len(mappings), 2500) rng = default_rng(SEED) sample = rng.choice(vids, size=n, replace=False) for vid in sample: frame = mappings[vid] bldg = buildings[frame["building"]] xs = [frame["x"], bldg["center"][0]] ys = [frame["y"], bldg["center"][1]] ax.add_line(Line2D(xs, ys, linestyle="-", marker='.', markevery=[0], linewidth=1, color=(0, 0, 0, 0.5))) ax.autoscale_view() ax.set_facecolor((0.50, 0.50, 0.50, 1.0)) ax.set_xlabel("Position (m)") ax.set_ylabel("Position (m)") ax.set_title("Vehicle Mapping Density, 10 AM") fig.colorbar(cm.ScalarMappable(norm=norm, cmap=HEAT_CM_1)) plt.show()
for key, label in plot.items(): axis = axis_row[current_axis] vmin, vmax = minmax[key] try: grid = (project_gas_pixel_grid( sim, resolution=resolution, project=key) / unweighted_grid) except: grid = (project_gas_pixel_grid( sim, resolution=resolution, project=key.replace("y", "ies").replace("ure", "ures")) / unweighted_grid) if vmin > vmax: normed_grid = 1.0 - Normalize(vmin=vmax, vmax=vmin)(grid) else: normed_grid = Normalize(vmin=vmin, vmax=vmax)(grid) axis.imshow( normed_grid, origin="lower", extent=[0, 1, 0, 1], cmap="RdBu", vmin=0.0, vmax=1.0, ) # Exact solution, a square! axis.plot( [0.25, 0.75, 0.75, 0.25, 0.25],
def spectrogram(data, samp_rate, per_lap=0.9, wlen=None, log=False, outfile=None, fmt=None, axes=None, dbscale=False, mult=8.0, cmap=obspy_sequential, zorder=None, title=None, show=True, sphinx=False, clip=[0.0, 1.0]): """ Computes and plots spectrogram of the input data. :param data: Input data :type samp_rate: float :param samp_rate: Samplerate in Hz :type per_lap: float :param per_lap: Percentage of overlap of sliding window, ranging from 0 to 1. High overlaps take a long time to compute. :type wlen: int or float :param wlen: Window length for fft in seconds. If this parameter is too small, the calculation will take forever. :type log: bool :param log: Logarithmic frequency axis if True, linear frequency axis otherwise. :type outfile: str :param outfile: String for the filename of output file, if None interactive plotting is activated. :type fmt: str :param fmt: Format of image to save :type axes: :class:`matplotlib.axes.Axes` :param axes: Plot into given axes, this deactivates the fmt and outfile option. :type dbscale: bool :param dbscale: If True 10 * log10 of color values is taken, if False the sqrt is taken. :type mult: float :param mult: Pad zeros to length mult * wlen. This will make the spectrogram smoother. :type cmap: :class:`matplotlib.colors.Colormap` :param cmap: Specify a custom colormap instance. If not specified, then the default ObsPy sequential colormap is used. :type zorder: float :param zorder: Specify the zorder of the plot. Only of importance if other plots in the same axes are executed. :type title: str :param title: Set the plot title :type show: bool :param show: Do not call `plt.show()` at end of routine. That way, further modifications can be done to the figure before showing it. :type sphinx: bool :param sphinx: Internal flag used for API doc generation, default False :type clip: [float, float] :param clip: adjust colormap to clip at lower and/or upper end. The given percentages of the amplitude range (linear or logarithmic depending on option `dbscale`) are clipped. """ import matplotlib.pyplot as plt # enforce float for samp_rate samp_rate = float(samp_rate) # set wlen from samp_rate if not specified otherwise if not wlen: wlen = samp_rate / 100. npts = len(data) # nfft needs to be an integer, otherwise a deprecation will be raised # XXX add condition for too many windows => calculation takes for ever nfft = int(_nearest_pow_2(wlen * samp_rate)) if nfft > npts: nfft = int(_nearest_pow_2(npts / 8.0)) if mult is not None: mult = int(_nearest_pow_2(mult)) mult = mult * nfft nlap = int(nfft * float(per_lap)) data = data - data.mean() end = npts / samp_rate # Here we call not plt.specgram as this already produces a plot # matplotlib.mlab.specgram should be faster as it computes only the # arrays # XXX mlab.specgram uses fft, would be better and faster use rfft specgram, freq, time = mlab.specgram(data, Fs=samp_rate, NFFT=nfft, pad_to=mult, noverlap=nlap) # db scale and remove zero/offset for amplitude if dbscale: specgram = 10 * np.log10(specgram[1:, :]) else: specgram = np.sqrt(specgram[1:, :]) freq = freq[1:] vmin, vmax = clip if vmin < 0 or vmax > 1 or vmin >= vmax: msg = "Invalid parameters for clip option." raise ValueError(msg) _range = float(specgram.max() - specgram.min()) vmin = specgram.min() + vmin * _range vmax = specgram.min() + vmax * _range norm = Normalize(vmin, vmax, clip=True) if not axes: fig = plt.figure() ax = fig.add_subplot(111) else: ax = axes # calculate half bin width halfbin_time = (time[1] - time[0]) / 2.0 halfbin_freq = (freq[1] - freq[0]) / 2.0 # argument None is not allowed for kwargs on matplotlib python 3.3 kwargs = { k: v for k, v in (('cmap', cmap), ('zorder', zorder)) if v is not None } if log: # pcolor expects one bin more at the right end freq = np.concatenate((freq, [freq[-1] + 2 * halfbin_freq])) time = np.concatenate((time, [time[-1] + 2 * halfbin_time])) # center bin time -= halfbin_time freq -= halfbin_freq # Log scaling for frequency values (y-axis) ax.set_yscale('log') # Plot times ax.pcolormesh(time, freq, specgram, norm=norm, **kwargs) else: # this method is much much faster! specgram = np.flipud(specgram) # center bin extent = (time[0] - halfbin_time, time[-1] + halfbin_time, freq[0] - halfbin_freq, freq[-1] + halfbin_freq) ax.imshow(specgram, interpolation="nearest", extent=extent, **kwargs) # set correct way of axis, whitespace before and after with window # length ax.axis('tight') ax.set_xlim(0, end) ax.grid(False) if axes: return ax ax.set_xlabel('Time [s]') ax.set_ylabel('Frequency [Hz]') if title: ax.set_title(title) if not sphinx: # ignoring all NumPy warnings during plot temp = np.geterr() np.seterr(all='ignore') plt.draw() np.seterr(**temp) if outfile: if fmt: fig.savefig(outfile, format=fmt) else: fig.savefig(outfile) elif show: plt.show() else: return fig