def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs): import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.collections import PatchCollection if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)] collection = PatchCollection(patches, **kwargs) if c is not None: collection.set_array(np.asarray(c)) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() if c is not None: plt.sci(collection) return collection
def pltfactcamera(*args, **kwargs): ax = plt.gca() fig = ax.get_figure() fig.canvas.mpl_connect("pick_event", onpick) ret = ax.factcamera(*args, **kwargs) plt.draw_if_interactive() plt.sci(ret) return ret
def contourf(cube, *args, **kwargs): """ Draws filled contours based on the given Cube. Kwargs: * coords: list of :class:`~iris.coords.Coord` objects or coordinate names Use the given coordinates as the axes for the plot. The order of the given coordinates indicates which axis to use for each, where the first element is the horizontal axis of the plot and the second element is the vertical axis of the plot. See :func:`matplotlib.pyplot.contourf` for details of other valid keyword arguments. """ coords = kwargs.get('coords') kwargs.setdefault('antialiased', True) result = _draw_2d_from_points('contourf', None, cube, *args, **kwargs) # Matplotlib produces visible seams between anti-aliased polygons. # But if the polygons are virtually opaque then we can cover the seams # by drawing anti-aliased lines *underneath* the polygon joins. # Figure out the alpha level for the contour plot if result.alpha is None: alpha = result.collections[0].get_facecolor()[0][3] else: alpha = result.alpha # If the contours are anti-aliased and mostly opaque then draw lines under # the seams. if result.antialiased and alpha > 0.95: levels = result.levels colors = [c[0] for c in result.tcolors] if result.extend == 'neither': levels = levels[1:-1] colors = colors[:-1] elif result.extend == 'min': levels = levels[:-1] colors = colors[:-1] elif result.extend == 'max': levels = levels[1:] colors = colors[:-1] else: colors = colors[:-1] if len(levels) > 0: # Draw the lines just *below* the polygons to ensure we minimise # any boundary shift. zorder = result.collections[0].zorder - .1 contour(cube, levels=levels, colors=colors, antialiased=True, zorder=zorder, coords=coords) # Restore the current "image" to 'result' rather than the mappable # resulting from the additional call to contour(). plt.sci(result) return result
def __set_current_image(ax, img): '''Helper to set the current image in pyplot mode. If the provided `ax` is not `None`, then we assume that the user is using the object API. In this case, the pyplot current image is not set. ''' if ax is None: import matplotlib.pyplot as plt plt.sci(img)
def plot_grid(grid: RegularGrid, ax: Axes=None, crs: CRS=None, band: Union[int, tuple]=-1, **kwargs): """ Plot a grid instance Parameters ---------- grid : RegularGrid raster data to plot ax : Axes, optional Axes to plot to [default plt.gca()] crs : CRS, optional Currently not supported band : int or tuple, optional Band(s) to plot. If *grid* has three bands, by default the three are plotted in false colour as RGB channels. Otherwise, the first band is plotted by default. If *band* is a tuple, it must have three integer elements. Notes ----- Additional arguments are passed to `matplotlib.pyplot.imshow` """ kwargs.setdefault("origin", "bottom") kwargs.setdefault("extent", grid.get_extent(crs=crs)) kwargs.setdefault("cmap", cm.binary_r) if crs is not None and crs != grid.crs: raise NotImplementedError("RegularGrid reprojection not supported") # compute the pixels that can actually be displayed # be slightly generous by using a factor of 0.75 to avoid choosing too low # of a resolution _, _, width, height = ax.bbox.bounds ny, nx = grid.size r = (max(int(0.75*ny//height), 1), max(int(0.75*nx//width), 1)) if band == -1: if len(grid.bands) == 3 and (band == -1): band = (0, 1, 2) else: band = 0 if isinstance(band, int): arr = grid[::r[0],::r[1],band] arr = np.ma.masked_equal(arr, grid.nodata) else: if len(band) not in (3, 4): raise ValueError("bands must be RGB or RGBA (length 3 or 4)") arr = np.dstack([grid[::r[0],::r[1],i] for i in band]).astype(np.float32) arr = np.ma.masked_equal(arr, grid.nodata) arr[:,:,:3] /= arr[:,:,:3].max() im = ax.imshow(arr, **kwargs) if ax == gca(): sci(im) return im
def smooth_contourf(*args,**kwargs): kwargs['filled'] = True ax=kwargs.pop('ax',pyp.gca()) washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ret = SmoothContour(ax,*args,**kwargs) pyp.draw_if_interactive() finally: ax.hold(washold) if ret._A is not None: pyp.sci(ret) return ret
def plot_structure(self, cmap='YlGnBu', site_radius=(0.03, 0.05), num_periods=1, **kwargs): """Plot the spatial structure with a colormap of :attr:`data` at the lattice sites Both the site size and color are used to display the data. Parameters ---------- cmap : str Matplotlib colormap to be used for the data. site_radius : Tuple[float, float] Min and max radius of lattice sites. This range will be used to visually represent the magnitude of the data. num_periods : int Number of times to repeat periodic boundaries. """ ax = plt.gca() ax.set_aspect('equal', 'datalim') ax.set_xlabel('x (nm)') ax.set_ylabel('y (nm)') def to_radii(data): if not isinstance(site_radius, (tuple, list)): return site_radius positive_data = data - data.min() maximum = positive_data.max() if not np.allclose(maximum, 0): delta = site_radius[1] - site_radius[0] return site_radius[0] + delta * positive_data / maximum else: return site_radius[1] props = structure_plot_properties(**kwargs) props['site'] = with_defaults(props['site'], radius=to_radii(self.data), cmap=cmap) collection = plot_sites(self.pos, self.data, **props['site']) hop = self.hoppings.tocoo() props['hopping'] = with_defaults(props['hopping'], colors='#bbbbbb') plot_hoppings(self.pos, hop, **props['hopping']) props['site']['alpha'] = props['hopping']['alpha'] = 0.5 plot_periodic_boundaries(self.pos, hop, self.boundaries, self.data, num_periods, **props) pltutils.despine(trim=True) pltutils.add_margin() plt.sci(collection) return collection
def plot(self, log = False, axes=None, **imshow_args): #Get current axes if not axes: axes = plt.gca() axes.set_title(self.__repr__()) axes.set_ylabel('pixels') axes.set_xlabel('pixels') if log: ret = axes.imshow(self.data, cmap=plt.cm.Greys_r, norm = LogNorm()) else: ret = axes.imshow(self.data, cmap=plt.cm.bone) plt.colorbar(ret) plt.sci(ret) return ret
def plot(): # Example from # <http://matplotlib.org/examples/pylab_examples/line_collection2.html> import matplotlib.pyplot as plt import numpy as np from matplotlib.collections import LineCollection fig = plt.figure() # In order to efficiently plot many lines in a single set of axes, # Matplotlib has the ability to add the lines all at once. Here is a # simple example showing how it is done. N = 50 x = np.arange(N) # Here are many sets of y to plot vs x ys = [x + i for i in x] # We need to set the plot limits, they will not autoscale ax = plt.axes() ax.set_xlim((np.amin(x), np.amax(x))) ax.set_ylim((np.amin(np.amin(ys)), np.amax(np.amax(ys)))) # colors is sequence of rgba tuples # linestyle is a string or dash tuple. Legal string values are # solid|dashed|dashdot|dotted. The dash tuple is (offset, # onoffseq) # where onoffseq is an even length tuple of on and off ink in # points. # If linestyle is omitted, 'solid' is used # See matplotlib.collections.LineCollection for more information # Make a sequence of x,y pairs line_segments = LineCollection( [list(zip(x, y)) for y in ys], linewidths=(0.5, 1, 1.5, 2), linestyles='dashdot' ) line_segments.set_array(x) ax.add_collection(line_segments) fig = plt.gcf() axcb = fig.colorbar(line_segments) axcb.set_label('Line Number') ax.set_title('Line Collection with mapped colors') plt.sci(line_segments) # This allows interactive changing of the colormap. return fig
def lines(xy, c='b', vmin=None, vmax=None, **kwargs): """ xy : sequence of array Coordinates of points in lines. `xy` is a sequence of array (line0, line1, ..., lineN) where line = [(x0, y0), (x1, y1), ... (xm, ym)] c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- collection : `~matplotlib.collections.LineCollection` """ if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) collection = LineCollection(xy, **kwargs) if c is not None: collection.set_array(np.asarray(c)) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() plt.draw_if_interactive() if c is not None: plt.sci(collection) return collection
def draw_specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=128, cmap=None, xextent=None, pad_to=None, sides='default', scale_by_freq=None, hold=None, **kwargs): ax = pyplot.gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() if hold is not None: ax.hold(hold) try: ret = specgram1(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, **kwargs) pyplot.draw_if_interactive() finally: ax.hold(washold) pyplot.sci(ret[-1]) return ret
def quiver(*args, **kw): ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kw.pop("hold", None) if hold is not None: ax.hold(hold) try: if not ax._hold: ax.cla() q = Quiver(ax, *args, **kw) ax.add_collection(q, autolim=True) ax.autoscale_view() draw_if_interactive() finally: ax.hold(washold) sci(q) return q
def plot(self, gamma=None, annotate=True, axes=None, **imshow_args): """ Plots the map object using matplotlib, in a method equivalent to plt.imshow() using nearest neighbour interpolation. Parameters ---------- gamma : float Gamma value to use for the color map annotate : bool If true, the data is plotted at it's natural scale; with title and axis labels. axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. **imshow_args : dict Any additional imshow arguments that should be used when plotting the image. Examples -------- #Simple Plot with color bar >>> aiamap.plot() >>> plt.colorbar() #Add a limb line and grid >>> aia.plot() >>> aia.draw_limb() >>> aia.draw_grid() """ #Get current axes if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) # Check that the image is properly oriented if (not wcsaxes_compat.is_wcsaxes(axes) and not np.array_equal(self.rotation_matrix, np.matrix(np.identity(2)))): warnings.warn("This map is not properly oriented. Plot axes may be incorrect", Warning) # Normal plot if annotate: axes.set_title("{name} {date:{tmf}}".format(name=self.name, date=parse_time(self.date), tmf=TIME_FORMAT)) # x-axis label if self.coordinate_system.x == 'HG': xlabel = 'Longitude [{lon}]'.format(lon=self.units.x) else: xlabel = 'X-position [{xpos}]'.format(xpos=self.units.x) # y-axis label if self.coordinate_system.y == 'HG': ylabel = 'Latitude [{lat}]'.format(lat=self.units.y) else: ylabel = 'Y-position [{ypos}]'.format(ypos=self.units.y) axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) cmap = deepcopy(self.cmap) if gamma is not None: cmap.set_gamma(gamma) kwargs = self._mpl_imshow_kwargs(axes, cmap) kwargs.update(imshow_args) if self.mask is None: ret = axes.imshow(self.data, **kwargs) else: ret = axes.imshow(np.ma.array(np.asarray(self.data), mask=self.mask), **kwargs) if wcsaxes_compat.is_wcsaxes(axes): wcsaxes_compat.default_wcs_grid(axes) #Set current image (makes colorbar work) plt.sca(axes) plt.sci(ret) return ret
def voltPlot(tree, workDir=None, neatoLayout=False): ''' Draw a color-coded map of the voltage drop on a feeder. Returns a matplotlib object. ''' # Get rid of schedules and climate: for key in tree.keys(): if tree[key].get("argument","") == "\"schedules.glm\"" or tree[key].get("tmyfile","") != "": del tree[key] # Make sure we have a voltDump: def safeInt(x): try: return int(x) except: return 0 biggestKey = max([safeInt(x) for x in tree.keys()]) tree[str(biggestKey*10)] = {"object":"voltdump","filename":"voltDump.csv"} # Run Gridlab. if not workDir: workDir = tempfile.mkdtemp() print "gridlabD runInFilesystem with no specified workDir. Working in", workDir gridlabOut = gridlabd.runInFilesystem(tree, attachments=[], workDir=workDir) with open(pJoin(workDir,'voltDump.csv'),'r') as dumpFile: reader = csv.reader(dumpFile) reader.next() # Burn the header. keys = reader.next() voltTable = [] for row in reader: rowDict = {} for pos,key in enumerate(keys): rowDict[key] = row[pos] voltTable.append(rowDict) # Calculate average node voltage deviation. First, helper functions. def pythag(x,y): ''' For right triangle with sides a and b, return the hypotenuse. ''' return math.sqrt(x**2+y**2) def digits(x): ''' Returns number of digits before the decimal in the float x. ''' return math.ceil(math.log10(x+1)) def avg(l): ''' Average of a list of ints or floats. ''' return sum(l)/len(l) # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob)==dict and ob.get('bustype','')=='SWING': feedVoltage = float(ob.get('nominal_voltage',1)) # Tot it all up. nodeVolts = {} for row in voltTable: allVolts = [] for phase in ['A','B','C']: phaseVolt = pythag(float(row['volt'+phase+'_real']), float(row['volt'+phase+'_imag'])) if phaseVolt != 0.0: if digits(phaseVolt)>3: # Normalize to 120 V standard phaseVolt = phaseVolt*(120/feedVoltage) allVolts.append(phaseVolt) nodeVolts[row.get('node_name','')] = avg(allVolts) # Color nodes by VOLTAGE. fGraph = feeder.treeToNxGraph(tree) voltChart = plt.figure(figsize=(10,10)) plt.axes(frameon = 0) plt.axis('off') if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) positions = nx.graphviz_layout(cleanG, prog='neato') else: positions = {n:fGraph.node[n].get('pos',(0,0)) for n in fGraph} edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes(fGraph, pos = positions, node_color = [nodeVolts.get(n,0) for n in fGraph.nodes()], linewidths = 0, node_size = 30, cmap = plt.cm.jet) plt.sci(nodeIm) plt.clim(110,130) plt.colorbar() return voltChart
def generateVoltChart(tree, rawOut, modelDir, neatoLayout=True): ''' Map the voltages on a feeder over time using a movie.''' # We need to timestamp frames with the system clock to make sure the browser caches them appropriately. genTime = str(datetime.datetime.now()).replace(':','.') # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob)==dict and ob.get('bustype','')=='SWING': feedVoltage = float(ob.get('nominal_voltage',1)) # Make a graph object. fGraph = feeder.treeToNxGraph(tree) if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) # was formerly : positions = nx.graphviz_layout(cleanG, prog='neato') but this threw an error positions = nx.nx_agraph.graphviz_layout(cleanG, prog='neato') else: rawPositions = {n:fGraph.node[n].get('pos',(0,0)) for n in fGraph} #HACK: the import code reverses the y coords. def yFlip(pair): try: return (pair[0], -1.0*pair[1]) except: return (0,0) positions = {k:yFlip(rawPositions[k]) for k in rawPositions} # Plot all time steps. nodeVolts = {} for step, stamp in enumerate(rawOut['aVoltDump.csv']['# timestamp']): # Build voltage map. nodeVolts[step] = {} for nodeName in [x for x in rawOut.get('aVoltDump.csv',{}).keys() + rawOut.get('1nVoltDump.csv',{}).keys() + rawOut.get('1mVoltDump.csv',{}).keys() if x != '# timestamp']: allVolts = [] for phase in ['a','b','c','1n','2n','1m','2m']: try: voltStep = rawOut[phase + 'VoltDump.csv'][nodeName][step] except: continue # the nodeName doesn't have the phase we're looking for. # HACK: Gridlab complex number format sometimes uses i, sometimes j, sometimes d. WTF? if type(voltStep) is str: voltStep = voltStep.replace('i','j') v = complex(voltStep) phaseVolt = abs(v) if phaseVolt != 0.0: if _digits(phaseVolt)>3: # Normalize to 120 V standard phaseVolt = phaseVolt*(120/feedVoltage) allVolts.append(phaseVolt) # HACK: Take average of all phases to collapse dimensionality. nodeVolts[step][nodeName] = avg(allVolts) # Line current calculations lineCurrents = {} if os.path.exists(pJoin(modelDir,'OH_line_current_phaseA.csv')): for step, stamp in enumerate(rawOut['OH_line_current_phaseA.csv']['# timestamp']): lineCurrents[step] = {} currentArray = [] # Finding currents of all phases on the line for key in [x for x in rawOut.get('OH_line_current_phaseA.csv',{}).keys() if x != '# timestamp']: currA = rawOut['OH_line_current_phaseA.csv'][key][step] currB = rawOut['OH_line_current_phaseB.csv'][key][step] currC = rawOut['OH_line_current_phaseC.csv'][key][step] flowDir = rawOut['OH_line_flow_direc.csv'][key][step] lineRating = rawOut['OH_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else : direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA),abs(currB),abs(currC)) directedCurrent = float(maxCurrent/lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'],tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent # Underground Lines if os.path.exists(pJoin(modelDir,'UG_line_current_phaseA.csv')): for step, stamp in enumerate(rawOut['UG_line_current_phaseA.csv']['# timestamp']): currentArray = [] # Finding currents of all phases on the line for key in [x for x in rawOut.get('UG_line_current_phaseA.csv',{}).keys() if x != '# timestamp']: currA = rawOut['UG_line_current_phaseA.csv'][key][step] currB = rawOut['UG_line_current_phaseB.csv'][key][step] currC = rawOut['UG_line_current_phaseC.csv'][key][step] flowDir = rawOut['UG_line_flow_direc.csv'][key][step] lineRating = rawOut['UG_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else : direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA),abs(currB),abs(currC)) directedCurrent = float(maxCurrent/lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'],tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent for step in lineCurrents: for edge in fGraph.edges(): if edge not in lineCurrents[step].keys(): lineCurrents[step][edge] = 0 # Draw animation. voltChart = plt.figure(figsize=(15,15)) plt.axes(frameon = 0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(0.0,'blue'),(0.25,'darkgray'),(0.75,'darkgray'),(1.0,'yellow')]) custom_cm.set_under(color='black') current_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(0.0,'green'),(0.999999,'green'),(1.0,'red')]) # current_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(-1.0,'green'),(0.0, 'gray'),(1.0,'red'),(1.0,'red')]) # use edge color to set color and dashness of overloaded/negative currents if len(lineCurrents)>0: edgeIm = nx.draw_networkx_edges(fGraph, pos = positions, edge_color = [lineCurrents[0].get(n,0) for n in fGraph.edges()], edge_cmap = current_cm) else: edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes(fGraph, pos = positions, node_color = [nodeVolts[0].get(n,0) for n in fGraph.nodes()], linewidths = 0, node_size = 30, cmap = custom_cm) plt.sci(nodeIm) plt.clim(110,130) plt.colorbar() plt.title(rawOut['aVoltDump.csv']['# timestamp'][0]) def update(step): nodeColors = np.array([nodeVolts[step].get(n,0) for n in fGraph.nodes()]) if len(lineCurrents)>0: edgeColors = np.array([lineCurrents[step].get(n,0) for n in fGraph.edges()]) edgeIm.set_array(edgeColors) plt.title(rawOut['aVoltDump.csv']['# timestamp'][step]) nodeIm.set_array(nodeColors) return nodeColors, mapTimestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") anim = FuncAnimation(voltChart, update, frames=len(rawOut['aVoltDump.csv']['# timestamp']), interval=200, blit=False) anim.save(pJoin(modelDir,'voltageChart_'+ mapTimestamp +'.mp4'), codec='h264', extra_args=['-pix_fmt', 'yuv420p']) # Reclaim memory by closing, deleting and garbage collecting the last chart. voltChart.clf() plt.close() del voltChart gc.collect() return genTime, mapTimestamp
def plot(self, axes=None, annotate=True, title="SunPy Composite Plot", **matplot_args): """Plots the composite map object by calling :meth:`~sunpy.map.GenericMap.plot` or :meth:`~sunpy.map.GenericMap.draw_contours`. By default, each map is plotted as an image. If a given map has levels defined (via :meth:`~sunpy.map.CompositeMap.set_levels`), that map will instead be plotted as contours. Parameters ---------- axes: `~matplotlib.axes.Axes` or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. annotate : `bool` If true, the data is plotted at it's natural scale; with title and axis labels. title : `str` Title of the composite map. **matplot_args : `dict` Any additional Matplotlib arguments that should be used when plotting. Returns ------- ret : `list` List of axes image or quad contour sets that have been plotted. Notes ----- If a line-width Matplotlib argument (``linewidth``, ``linewidths``, or ``lw``) is provided, it will apply only to those maps that are plotted as contours. If a transformation is required to overlay the maps with the correct alignment, the plot limits may need to be manually set because Matplotlib autoscaling may not work as intended. """ # If axes are not provided, create a WCSAxes based on the first map if not axes: axes = wcsaxes_compat.gca_wcs(self._maps[0].wcs) if annotate: axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0], self._maps[0].spatial_units[0])) axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1], self._maps[0].spatial_units[1])) axes.set_title(title) # Define a list of plotted objects ret = [] # Plot layers of composite map for m in self._maps: # Parameters for plotting params = { "alpha": m.alpha, "zorder": m.zorder, } params.update(matplot_args) # The request to show a map layer rendered as a contour is indicated by a # non False levels property. if m.levels is False: # Check if any linewidth argument is provided, if so, then delete it from params. for item in ['linewidth', 'linewidths', 'lw']: if item in matplot_args: del params[item] # We tell GenericMap.plot() that we need to autoalign the map if wcsaxes_compat.is_wcsaxes(axes): params['autoalign'] = True params['annotate'] = False ret.append(m.plot(**params)) else: ret.append(m.draw_contours(m.levels, **params)) # Set the label of the first line so a legend can be created ret[-1].collections[0].set_label(m.name) # Adjust axes extents to include all data axes.axis('image') # Set current image (makes colorbar work) plt.sci(ret[0]) return ret
def circles(x, y, s, ax, c='b', vmin=None, vmax=None, **kwargs): """ Make a scatter of circles plot of x vs y, where x and y are sequence like objects of the same lengths. The size of circles are in data scale. Parameters ---------- x,y : scalar or array_like, shape (n, ) Input data s : scalar or array_like, shape (n, ) Radius of circle in data unit. c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- paths : `~matplotlib.collections.PathCollection` Examples -------- a = np.arange(11) circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none') plt.colorbar() License -------- This code is under [The BSD 3-Clause License] (http://opensource.org/licenses/BSD-3-Clause) """ from matplotlib.patches import Circle from matplotlib.collections import PatchCollection import numpy as np import matplotlib.pyplot as plt #if np.isscalar(c): # kwargs.setdefault('color', c) # c = None if c is not None: kwargs.setdefault('color', c) c = None if 'zorder' in kwargs: kwargs.setdefault('zorder', kwargs.pop('zorder')) if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)] collection = PatchCollection(patches, **kwargs) #if c is not None: # collection.set_array(np.asarray(c)) # collection.set_clim(vmin, vmax) #ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() if c is not None: plt.sci(collection) return collection # example usage # plt.figure(figsize=(6,4)) # ax = plt.subplot(aspect='equal') # # #plot a set of circle # a = np.arange(11) # out = circles(a, a, a*0.2, c=a, alpha=0.5, ec='none') # plt.colorbar() # # #plot one circle (the lower-right one) # circles(1, 0, 0.4, 'r', ls='--', lw=5, fc='none', transform=ax.transAxes) # xlim(0,10) # ylim(0,10) # plt.show() # # exit(1)
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs): """ Make a scatter of circles plot of x vs y, where x and y are sequence like objects of the same lengths. The size of circles are in data scale. Parameters ---------- x,y : scalar or array_like, shape (n, ) Input data s : scalar or array_like, shape (n, ) Radius of circle in data unit. c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- paths : `~matplotlib.collections.PathCollection` Examples -------- a = np.arange(11) circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none') plt.colorbar() License -------- This code is under [The BSD 3-Clause License] (http://opensource.org/licenses/BSD-3-Clause) (http://stackoverflow.com/questions/9081553/python-scatter-plot-size-and-style-of-the-marker/24567352#24567352) """ if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)] collection = PatchCollection(patches, **kwargs) if c is not None: collection.set_array(np.asarray(c)) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() if c is not None: plt.sci(collection) return collection, patches
def plot(self, gamma=None, annotate=True, axes=None, **imshow_args): """ Plots the map object using matplotlib, in a method equivalent to plt.imshow() using nearest neighbour interpolation. Parameters ---------- gamma : float Gamma value to use for the color map annotate : bool If true, the data is plotted at it's natural scale; with title and axis labels. axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. **imshow_args : dict Any additional imshow arguments that should be used when plotting the image. Examples -------- #Simple Plot with color bar plt.figure() aiamap.plot() plt.colorbar() #Add a limb line and grid aia.plot() aia.draw_limb() aia.draw_grid() """ #Get current axes if not axes: axes = plt.gca() # Normal plot if annotate: axes.set_title("%s %s" % (self.name, self.date)) # x-axis label if self.coordinate_system['x'] == 'HG': xlabel = 'Longitude [%s]' % self.units['x'] else: xlabel = 'X-position [%s]' % self.units['x'] # y-axis label if self.coordinate_system['y'] == 'HG': ylabel = 'Latitude [%s]' % self.units['y'] else: ylabel = 'Y-position [%s]' % self.units['y'] axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) # Determine extent extent = self.xrange + self.yrange cmap = copy(self.cmap) if gamma is not None: cmap.set_gamma(gamma) #make imshow kwargs a dict kwargs = {'origin':'lower', 'cmap':cmap, 'norm':self.norm(), 'extent':extent, 'interpolation':'nearest'} kwargs.update(imshow_args) ret = axes.imshow(self, **kwargs) #Set current image (makes colorbar work) plt.sci(ret) return ret
def plot( self, axes=None, annotate=True, # pylint: disable=W0613 title="SunPy Composite Plot", **matplot_args): """Plots the composite map object using matplotlib Parameters ---------- axes: `~matplotlib.axes.Axes` or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. annotate : `bool` If true, the data is plotted at it's natural scale; with title and axis labels. title : `str` Title of the composite map. **matplot_args : `dict` Matplotlib Any additional imshow arguments that should be used when plotting. Returns ------- ret : `list` List of axes image or quad contour sets that have been plotted. """ # Get current axes if not axes: axes = plt.gca() if annotate: axes.set_xlabel( axis_labels_from_ctype(self._maps[0].coordinate_system[0], self._maps[0].spatial_units[0])) axes.set_ylabel( axis_labels_from_ctype(self._maps[0].coordinate_system[1], self._maps[0].spatial_units[1])) axes.set_title(title) # Define a list of plotted objects ret = [] # Plot layers of composite map for m in self._maps: # Parameters for plotting bl = m._get_lon_lat(m.bottom_left_coord) tr = m._get_lon_lat(m.top_right_coord) x_range = list( u.Quantity([bl[0], tr[0]]).to(m.spatial_units[0]).value) y_range = list( u.Quantity([bl[1], tr[1]]).to(m.spatial_units[1]).value) params = { "origin": "lower", "extent": x_range + y_range, "cmap": m.plot_settings['cmap'], "norm": m.plot_settings['norm'], "alpha": m.alpha, "zorder": m.zorder, } params.update(matplot_args) # The request to show a map layer rendered as a contour is indicated by a # non False levels property. If levels is False, then the layer is # rendered using imshow. if m.levels is False: # Check for the presence of masked map data if m.mask is None: ret.append(axes.imshow(m.data, **params)) else: ret.append( axes.imshow( np.ma.array(np.asarray(m.data), mask=m.mask), **params)) else: # Check for the presence of masked map data if m.mask is None: ret.append(axes.contour(m.data, m.levels, **params)) else: ret.append( axes.contour( np.ma.array(np.asarray(m.data), mask=m.mask), m.levels, **params)) # Set the label of the first line so a legend can be created ret[-1].collections[0].set_label(m.name) # Adjust axes extents to include all data axes.axis('image') # Set current image (makes colorbar work) plt.sci(ret[0]) return ret
def imshow(plots, **kwargs): # Imshow wrapper with extended functionality plots = np.array(plots) plots = np.atleast_2d(plots) if plots.dtype == object else np.array( [[plots]]) m, n = (plots.shape[0], plots.shape[1]) fig, axs = plt.subplots(m, n) if m == 1 and n == 1: axs = np.array([[axs]], dtype='object') elif m == 1: axs = np.array(axs, dtype='object')[None, :] elif n == 1: axs = np.array(axs, dtype='object')[:, None] else: axs = np.array(axs, dtype='object') maxs = [] mins = [] for i in xrange(m): for j in xrange(n): maxs.append(plots[i, j].max()) mins.append(plots[i, j].min()) show_ticks = True if not "show_ticks" in kwargs else kwargs[ "show_ticks"] # Show ticks colorbar = "same" if not "colorbar" in kwargs else kwargs[ "colorbar"] # Show colorbar cmap = default_cmap if not "cmap" in kwargs else kwargs[ "cmap"] # Specify colormap lim = [ min(mins), max(maxs) ] if not "lim" in kwargs else kwargs["lim"] # Limits of the colorbar symm = False if not "symm" in kwargs else kwargs[ "symm"] # Symmetric limits of the colorbar imgs = np.zeros((m, n), dtype='object') for i in xrange(m): for j in xrange(n): ax = axs[i, j] p = plots[i, j] if colorbar == "same": dummy = np.zeros(p.shape) dummy[0, 0] = lim[0] dummy[0, 1] = lim[1] dummy[1, 0] = -lim[0] if symm else 0. dummy[1, 1] = -lim[1] if symm else 0. img = ax.imshow(dummy, cmap=cmap) img.set_data(p) else: img = ax.imshow(p, cmap=cmap) if colorbar: div = make_axes_locatable(ax) cax = div.append_axes("right", size="5%", pad=0.1) plt.colorbar(img, cax=cax) plt.sca(ax) plt.sci(img) ax.xaxis.set_visible(show_ticks) ax.yaxis.set_visible(show_ticks) imgs[i, j] = img if imgs.shape[0] == 1 and imgs.shape[1] == 1: return imgs[0][0] if imgs.shape[0] == 1 or imgs.shape[1] == 1: return np.array(imgs).flatten() return imgs
# observing it for changes in cmap or norm. class ImageFollower: 'update image in response to changes in clim or cmap on another image' def __init__(self, follower): self.follower = follower def __call__(self, leader): self.follower.set_cmap(leader.get_cmap()) self.follower.set_clim(leader.get_clim()) norm = colors.Normalize(vmin=vmin, vmax=vmax) for i, im in enumerate(images): im.set_norm(norm) if i > 0: images[0].callbacksSM.connect('changed', ImageFollower(im)) # The colorbar is also based on this master image. fig.colorbar(images[0], cax, orientation='horizontal') # We need the following only if we want to run this interactively and # modify the colormap: axes(ax[0]) # Return the current axes to the first one, sci(images[0]) # because the current image must be in current axes. show()
def plot(data, mesh, shade_pml=False, axis=None, ticks=True, update=None, slice3d=(0, 0, 0), **kwargs): """ Assumes that data has no ghost padding.""" data.shape = -1, 1 sh_bc = mesh.shape(include_bc=True) sh_primary = mesh.shape() if data.shape == sh_bc: has_bc = True plot_shape = mesh.shape(include_bc=True, as_grid=True) elif data.shape == sh_primary: has_bc = False plot_shape = mesh.shape(as_grid=True) else: raise ValueError('Shape mismatch between domain and data.') if axis is None: ax = plt.gca() else: ax = axis data = data.reshape(plot_shape) if mesh.dim == 1: if update is None: zs, = mesh.mesh_coords() ret, = ax.plot(zs, data) if has_bc: ax.axvline(mesh.domain.parameters['z']['lbound'], color='r') ax.axvline(mesh.domain.parameters['z']['rbound'], color='r') else: update.set_ydata(data) ret = update if mesh.dim == 2: data = data.T if update is None: im = ax.imshow(data, interpolation='nearest', aspect='auto', **kwargs) if ticks: mesh_tickers(mesh) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'x', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml) else: update.set_data(data) im = update # Update current image for the colorbar plt.sci(im) ret = im if mesh.dim == 3: if update is None: # X-Y plot ax = plt.subplot(2, 2, 1) imslice = int(slice3d[2]) # z slice pltdata = data[:, :, imslice:(imslice + 1)].squeeze() imxy = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs) if ticks: mesh_tickers(mesh, ('y', 'x')) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'y', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'x', 'TB', shade_pml=shade_pml) # X-Z plot ax = plt.subplot(2, 2, 2) imslice = int(slice3d[1]) # y slice pltdata = data[:, imslice:(imslice + 1), :].squeeze().T imxz = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs) if ticks: mesh_tickers(mesh, ('x', 'z')) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'x', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml) # Y-Z plot ax = plt.subplot(2, 2, 3) imslice = int(slice3d[0]) # x slice pltdata = data[imslice:(imslice + 1), :, :].squeeze().T imyz = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs) if ticks: mesh_tickers(mesh, ('y', 'z')) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'y', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml) update = [imxy, imxz, imyz] plt.sci(imyz) else: imslice = int(slice3d[2]) # z slice pltdata = data[:, :, imslice:(imslice + 1)].squeeze() update[0].set_data(pltdata) imslice = int(slice3d[1]) # y slice pltdata = data[:, imslice:(imslice + 1), :].squeeze().T update[1].set_data(pltdata) imslice = int(slice3d[0]) # x slice pltdata = data[imslice:(imslice + 1), :, :].squeeze().T update[2].set_data(pltdata) ret = update return ret
def voltPlot(omd, workDir=None, neatoLayout=False): ''' Draw a color-coded map of the voltage drop on a feeder. Returns a matplotlib object. ''' tree = omd.get('tree', {}) # # Get rid of schedules and climate: for key in tree.keys(): if tree[key].get("argument", "") == "\"schedules.glm\"" or tree[key].get( "tmyfile", "") != "": del tree[key] # Make sure we have a voltDump: def safeInt(x): try: return int(x) except: return 0 biggestKey = max([safeInt(x) for x in tree.keys()]) tree[str(biggestKey * 10)] = { "object": "voltdump", "filename": "voltDump.csv" } # Run Gridlab. if not workDir: workDir = tempfile.mkdtemp() print "gridlabD runInFilesystem with no specified workDir. Working in", workDir gridlabOut = gridlabd.runInFilesystem(tree, attachments=omd.get( 'attachments', {}), workDir=workDir) with open(pJoin(workDir, 'voltDump.csv'), 'r') as dumpFile: reader = csv.reader(dumpFile) reader.next() # Burn the header. keys = reader.next() voltTable = [] for row in reader: rowDict = {} for pos, key in enumerate(keys): rowDict[key] = row[pos] voltTable.append(rowDict) # Calculate average node voltage deviation. First, helper functions. def pythag(x, y): ''' For right triangle with sides a and b, return the hypotenuse. ''' return math.sqrt(x**2 + y**2) def digits(x): ''' Returns number of digits before the decimal in the float x. ''' return math.ceil(math.log10(x + 1)) def avg(l): ''' Average of a list of ints or floats. ''' return sum(l) / len(l) # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob) == dict and ob.get('bustype', '') == 'SWING': feedVoltage = float(ob.get('nominal_voltage', 1)) # Tot it all up. nodeVolts = {} for row in voltTable: allVolts = [] for phase in ['A', 'B', 'C']: phaseVolt = pythag(float(row['volt' + phase + '_real']), float(row['volt' + phase + '_imag'])) if phaseVolt != 0.0: if digits(phaseVolt) > 3: # Normalize to 120 V standard phaseVolt = phaseVolt * (120 / feedVoltage) allVolts.append(phaseVolt) nodeVolts[row.get('node_name', '')] = avg(allVolts) # Color nodes by VOLTAGE. fGraph = feeder.treeToNxGraph(tree) voltChart = plt.figure(figsize=(15, 15)) plt.axes(frameon=0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) positions = graphviz_layout(cleanG, prog='neato') else: positions = {n: fGraph.node[n].get('pos', (0, 0)) for n in fGraph} edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes( fGraph, pos=positions, node_color=[nodeVolts.get(n, 0) for n in fGraph.nodes()], linewidths=0, node_size=30, cmap=plt.cm.jet) plt.sci(nodeIm) plt.clim(110, 130) plt.colorbar() return voltChart
def showMatrix(matrix, x_array=None, y_array=None, **kwargs): """Show a matrix using :meth:`~matplotlib.axes.Axes.imshow`. Curves on x- and y-axis can be added. :arg matrix: matrix to be displayed :type matrix: :class:`~numpy.ndarray` :arg x_array: data to be plotted above the matrix :type x_array: :class:`~numpy.ndarray` :arg y_array: data to be plotted on the left side of the matrix :type y_array: :class:`~numpy.ndarray` :arg percentile: a percentile threshold to remove outliers, i.e. only showing data within *p*-th to *100-p*-th percentile :type percentile: float :arg interactive: turn on or off the interactive options :type interactive: bool :arg xtickrotation: how much to rotate the xticklabels in degrees default is 0 :type xtickrotation: float """ from matplotlib import ticker from matplotlib.gridspec import GridSpec from matplotlib.collections import LineCollection from matplotlib.pyplot import gca, sca, sci, colorbar, subplot from .drawtools import drawTree p = kwargs.pop('percentile', None) vmin = vmax = None if p is not None: vmin = np.percentile(matrix, p) vmax = np.percentile(matrix, 100-p) vmin = kwargs.pop('vmin', vmin) vmax = kwargs.pop('vmax', vmax) vcenter = kwargs.pop('vcenter', None) norm = kwargs.pop('norm', None) if vcenter is not None and norm is None: if PY3K: try: from matplotlib.colors import DivergingNorm except ImportError: from matplotlib.colors import TwoSlopeNorm as DivergingNorm norm = DivergingNorm(vmin=vmin, vcenter=0., vmax=vmax) else: LOGGER.warn('vcenter cannot be used in Python 2 so norm remains None') lw = kwargs.pop('linewidth', 1) W = H = kwargs.pop('ratio', 6) ticklabels = kwargs.pop('ticklabels', None) xticklabels = kwargs.pop('xticklabels', ticklabels) yticklabels = kwargs.pop('yticklabels', ticklabels) xtickrotation = kwargs.pop('xtickrotation', 0.) show_colorbar = kwargs.pop('colorbar', True) cb_extend = kwargs.pop('cb_extend', 'neither') allticks = kwargs.pop('allticks', False) # this argument is temporary and will be replaced by better implementation interactive = kwargs.pop('interactive', True) cmap = kwargs.pop('cmap', 'jet') origin = kwargs.pop('origin', 'lower') try: from Bio import Phylo except ImportError: raise ImportError('Phylo module could not be imported. ' 'Reinstall ProDy or install Biopython ' 'to solve the problem.') tree_mode_y = isinstance(y_array, Phylo.BaseTree.Tree) tree_mode_x = isinstance(x_array, Phylo.BaseTree.Tree) if x_array is not None and y_array is not None: nrow = 2; ncol = 2 i = 1; j = 1 width_ratios = [1, W] height_ratios = [1, H] aspect = 'auto' elif x_array is not None and y_array is None: nrow = 2; ncol = 1 i = 1; j = 0 width_ratios = [W] height_ratios = [1, H] aspect = 'auto' elif x_array is None and y_array is not None: nrow = 1; ncol = 2 i = 0; j = 1 width_ratios = [1, W] height_ratios = [H] aspect = 'auto' else: nrow = 1; ncol = 1 i = 0; j = 0 width_ratios = [W] height_ratios = [H] aspect = kwargs.pop('aspect', None) main_index = (i, j) upper_index = (i-1, j) left_index = (i, j-1) complex_layout = nrow > 1 or ncol > 1 ax1 = ax2 = ax3 = None if complex_layout: gs = GridSpec(nrow, ncol, width_ratios=width_ratios, height_ratios=height_ratios, hspace=0., wspace=0.) ## draw matrix if complex_layout: ax3 = subplot(gs[main_index]) else: ax3 = gca() im = ax3.imshow(matrix, aspect=aspect, vmin=vmin, vmax=vmax, norm=norm, cmap=cmap, origin=origin, **kwargs) #ax3.set_xlim([-0.5, matrix.shape[0]+0.5]) #ax3.set_ylim([-0.5, matrix.shape[1]+0.5]) if xticklabels is not None: ax3.xaxis.set_major_formatter(ticker.IndexFormatter(xticklabels)) if yticklabels is not None and ncol == 1: ax3.yaxis.set_major_formatter(ticker.IndexFormatter(yticklabels)) if allticks: ax3.xaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.)) ax3.yaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.)) else: locator = ticker.AutoLocator() locator.set_params(integer=True) minor_locator = ticker.AutoMinorLocator() ax3.xaxis.set_major_locator(locator) ax3.xaxis.set_minor_locator(minor_locator) locator = ticker.AutoLocator() locator.set_params(integer=True) minor_locator = ticker.AutoMinorLocator() ax3.yaxis.set_major_locator(locator) ax3.yaxis.set_minor_locator(minor_locator) if ncol > 1: ax3.yaxis.set_major_formatter(ticker.NullFormatter()) ## draw x_ and y_array lines = [] if nrow > 1: ax1 = subplot(gs[upper_index]) if tree_mode_x: Y, X = drawTree(x_array, label_func=None, orientation='vertical', inverted=True) miny = min(Y.values()) maxy = max(Y.values()) minx = min(X.values()) maxx = max(X.values()) ax1.set_xlim(minx-.5, maxx+.5) ax1.set_ylim(miny, 1.05*maxy) else: ax1.set_xticklabels([]) y = x_array xp, yp = interpY(y) points = np.array([xp, yp]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcy = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap) lines.append(lcy) ax1.add_collection(lcy) ax1.set_xlim(xp.min()-.5, xp.max()+.5) ax1.set_ylim(yp.min(), yp.max()) if ax3.xaxis_inverted(): ax2.invert_xaxis() ax1.axis('off') if ncol > 1: ax2 = subplot(gs[left_index]) if tree_mode_y: X, Y = drawTree(y_array, label_func=None, inverted=True) miny = min(Y.values()) maxy = max(Y.values()) minx = min(X.values()) maxx = max(X.values()) ax2.set_ylim(miny-.5, maxy+.5) ax2.set_xlim(minx, 1.05*maxx) else: ax2.set_xticklabels([]) y = y_array xp, yp = interpY(y) points = np.array([yp, xp]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcx = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap) lines.append(lcx) ax2.add_collection(lcx) ax2.set_xlim(yp.min(), yp.max()) ax2.set_ylim(xp.min()-.5, xp.max()+.5) ax2.invert_xaxis() if ax3.yaxis_inverted(): ax2.invert_yaxis() ax2.axis('off') ## draw colorbar sca(ax3) cb = None if show_colorbar: if nrow > 1: axes = [ax1, ax2, ax3] while None in axes: axes.remove(None) s = H / (H + 1.) cb = colorbar(mappable=im, ax=axes, anchor=(0, 0), shrink=s, extend=cb_extend) else: cb = colorbar(mappable=im, extend=cb_extend) sca(ax3) sci(im) if interactive: from prody.utilities import ImageCursor from matplotlib.pyplot import connect cursor = ImageCursor(ax3, im) connect('button_press_event', cursor.onClick) ax3.tick_params(axis='x', rotation=xtickrotation) return im, lines, cb
# linestyle is a string or dash tuple. Legal string values are # solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) # where onoffseq is an even length tuple of on and off ink in points. # If linestyle is omitted, 'solid' is used # See :class:`matplotlib.collections.LineCollection` for more information # Make a sequence of x,y pairs line_segments = LineCollection([np.column_stack([x, y]) for y in ys], linewidths=(0.5, 1, 1.5, 2), linestyles='solid') line_segments.set_array(x) ax.add_collection(line_segments) axcb = fig.colorbar(line_segments) axcb.set_label('Line Number') ax.set_title('Line Collection with mapped colors') plt.sci(line_segments) # This allows interactive changing of the colormap. plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.collections matplotlib.collections.LineCollection
def contourf(cube, *args, **kwargs): """ Draws filled contours based on the given Cube. Kwargs: * coords: list of :class:`~iris.coords.Coord` objects or coordinate names. Use the given coordinates as the axes for the plot. The order of the given coordinates indicates which axis to use for each, where the first element is the horizontal axis of the plot and the second element is the vertical axis of the plot. * axes: the :class:`matplotlib.axes.Axes` to use for drawing. Defaults to the current axes if none provided. See :func:`matplotlib.pyplot.contourf` for details of other valid keyword arguments. """ coords = kwargs.get('coords') kwargs.setdefault('antialiased', True) result = _draw_2d_from_points('contourf', None, cube, *args, **kwargs) # Matplotlib produces visible seams between anti-aliased polygons. # But if the polygons are virtually opaque then we can cover the seams # by drawing anti-aliased lines *underneath* the polygon joins. # Figure out the alpha level for the contour plot if result.alpha is None: alpha = result.collections[0].get_facecolor()[0][3] else: alpha = result.alpha # If the contours are anti-aliased and mostly opaque then draw lines under # the seams. if result.antialiased and alpha > 0.95: levels = result.levels colors = [c[0] for c in result.tcolors] if result.extend == 'neither': levels = levels[1:-1] colors = colors[:-1] elif result.extend == 'min': levels = levels[:-1] colors = colors[:-1] elif result.extend == 'max': levels = levels[1:] colors = colors[:-1] else: colors = colors[:-1] if len(levels) > 0: # Draw the lines just *below* the polygons to ensure we minimise # any boundary shift. zorder = result.collections[0].zorder - .1 axes = kwargs.get('axes', None) contour(cube, levels=levels, colors=colors, antialiased=True, zorder=zorder, coords=coords, axes=axes) # Restore the current "image" to 'result' rather than the mappable # resulting from the additional call to contour(). if axes: axes._sci(result) else: plt.sci(result) return result
def plot_path(xy_arr, segments_weights=None, clip=True, figsize=(6, 4), title='', change_width=True, change_color=True, screen_lims=False, colorbar=True, weight_threshold=None, show_joints=False, feed_lines=False, width_mult=3, **kwargs): """Plot trajectories on a screen and highlight segments with color and linewidth""" # Reshape xy_arr to a sequence of segments [[(x0,y0),(x1,y1)],[(x1,y1),(x2,y2)],...] if clip: xy_arr = np.clip(xy_arr, 0, 1) if feed_lines: segments = xy_arr else: segments = np.array(xy_to_segments(xy_arr)) sw = np.array(segments_weights) if segments_weights is not None else None cmap = None linewidths = None # Show weights with color and linewidth if (sw is not None) and change_color: cmap = plt.get_cmap('plasma') if (sw is not None) and change_width: linewidths = (1 + (sw-min(sw)/(max(sw)-min(sw) + 1e-16)) * width_mult) # Plot only segments where weight is higher than zero: if (sw is not None) and (weight_threshold is not None): segments = segments[sw > weight_threshold] sw = sw[sw > weight_threshold] fig, ax = plt.subplots(1, 1, figsize=figsize) # Convert data to LineCollection line_segments = LineCollection(segments, linewidths=linewidths, linestyles='solid', cmap=cmap, **kwargs)#, norm=plt.Normalize(min(fw), max(fw))) line_segments.set_array(sw) ax.add_collection(line_segments) if show_joints: # x, y start segment points + last x, y point from segments ends x = np.concatenate([segments[:, 0][:, 0], [segments[:, 1][-1, 0]]]) y = np.concatenate([segments[:, 0][:, 1], [segments[:, 1][-1, 1]]]) ax.scatter(x, y, s=10) # Add colorbar for weights if (sw is not None) and colorbar: axcb = fig.colorbar(line_segments) axcb.set_label('Activation') plt.sci(line_segments) # this allows interactive changing of the colormap. # Set plot limits if screen_lims: ax.set_ylim([-0.05, 1.05]) ax.set_xlim([-0.05, 1.05]) else: ax.set_xlim((np.amin(xy_arr[:, 0] - 0.05), np.amax(xy_arr[:, 0]) + 0.05)) ax.set_ylim((np.amin(xy_arr[:, 1] - 0.05), np.amax(xy_arr[:, 1]) + 0.05)) ax.set_title(title, fontsize=12, y=1.1) ax.invert_yaxis() # invert y axis according to the eye-tracking data ax.xaxis.tick_top() return fig
def drawPlot(tree, nodeDict=None, edgeDict=None, edgeLabsDict=None, displayLabs=False, customColormap=False, perUnitScale=False, rezSqIn=400, neatoLayout=False, nodeFlagBounds=[-float('inf'), float('inf')], defaultNodeVal=1): ''' Draw a color-coded map of the voltage drop on a feeder. path is the full path to the GridLAB-D .glm file or OMF .omd file. workDir is where GridLAB-D will run, if it's None then a temp dir is used. neatoLayout=True means the circuit is displayed using a force-layout approach. edgeLabs property must be either 'Name', 'Current', 'Power', 'Rating', 'PercentOfRating', or None nodeLabs property must be either 'Name', 'Voltage', 'VoltageImbalance', or None edgeCol and nodeCol can be set to false to avoid coloring edges or nodes customColormap=True means use a one that is nicely scaled to perunit values highlighting extremes. Returns a matplotlib object.''' # Be quiet matplotlib: # warnings.filterwarnings('ignore') # Build the graph. fGraph = feeder.treeToNxGraph(tree) # TODO: consider whether we can set figsize dynamically. wlVal = int(math.sqrt(float(rezSqIn))) chart = plt.figure(figsize=(wlVal, wlVal)) plt.axes(frameon=0) plt.axis('off') chart.gca().set_aspect('equal') plt.tight_layout() # Need to get edge names from pairs of connected node names. edgeNames = [] for e in fGraph.edges(): edgeNames.append((fGraph.edges[e].get('name', 'BLANK')).replace('"', '')) #set axes step equal if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) positions = graphviz_layout(cleanG, prog='neato') else: positions = { n: fGraph.nodes[n].get('pos', (0, 0))[::-1] for n in fGraph } #create custom colormap if customColormap: custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list( 'custColMap', [(0.0, 'blue'), (0.15, 'darkgray'), (0.7, 'darkgray'), (1.0, 'red')]) custom_cm.set_under(color='black') else: custom_cm = plt.cm.get_cmap('viridis') drawColorbar = False emptyColors = {} #draw edges with or without colors if edgeDict != None: drawColorbar = True edgeList = [edgeDict.get(n, 1) for n in edgeNames] else: edgeList = [emptyColors.get(n, .6) for n in edgeNames] edgeIm = nx.draw_networkx_edges(fGraph, pos=positions, edge_color=edgeList, width=1, edge_cmap=custom_cm) #draw edge labels if displayLabs: edgeLabelsIm = nx.draw_networkx_edge_labels(fGraph, pos=positions, edge_labels=edgeLabsDict, font_size=8) # draw nodes with or without color if nodeDict != None: nodeList = [nodeDict.get(n, defaultNodeVal) for n in fGraph.nodes()] drawColorbar = True else: nodeList = [emptyColors.get(n, .6) for n in fGraph.nodes()] if perUnitScale: vmin = 0 vmax = 1.25 else: vmin = None vmax = None edgecolors = ['None'] * len(nodeList) for i in range(len(nodeList)): if nodeList[i] < nodeFlagBounds[0]: edgecolors[i] = '#ffa500' if nodeList[i] > nodeFlagBounds[1]: edgecolors[i] = 'r' nodeIm = nx.draw_networkx_nodes(fGraph, pos=positions, node_color=nodeList, edgecolors=edgecolors, linewidths=2, node_size=30, vmin=vmin, vmax=vmax, cmap=custom_cm) #draw node labels if displayLabs and nodeDict != None: nodeLabelsIm = nx.draw_networkx_labels(fGraph, pos=positions, labels=nodeDict, font_size=8) plt.sci(nodeIm) # plt.clim(110,130) if drawColorbar: plt.colorbar() return chart
def visualize(self, vertex_data=None, vertex_inds=None, center_data=None, center_inds=None, volume_data=None, vertex_size=80, vmin=None, vmax=None, new_figure=True): if self.dim not in (2, 3): raise ValueError('Can only visualize samples of dimension 2, 3') vertices = np.array(self.vertices).astype(float) * self.dimensions[np.newaxis, :] + self.ranges[:, 0] centers = np.array(self.centers).astype(float) * self.dimensions[np.newaxis, :] + self.ranges[:, 0] if vmin is None: vmin = np.inf if vertex_data is not None: vmin = min(vmin, np.min(vertex_data)) if center_data is not None: vmin = min(vmin, np.min(center_data)) if volume_data is not None: vmin = min(vmin, np.min(volume_data)) if vmax is None: vmax = -np.inf if vertex_data is not None: vmax = max(vmax, np.max(vertex_data)) if center_data is not None: vmax = max(vmax, np.max(center_data)) if volume_data is not None: vmax = max(vmax, np.max(volume_data)) if self.dim == 2: import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle if new_figure: plt.figure() plt.xlim(self.ranges[0]) plt.ylim(self.ranges[1]) # draw volumes rects = [] for leaf, level in zip(self.vertex_ids, self.levels): size = 1. / 2**level ll = self.vertices[leaf[0]] * self.dimensions + self.ranges[:, 0] rects.append(Rectangle(ll, size * self.dimensions[0], size * self.dimensions[1], facecolor='white', zorder=-1)) if volume_data is not None: coll = PatchCollection(rects, match_original=False) coll.set_array(volume_data) coll.set_clim(vmin, vmax) else: coll = PatchCollection(rects, match_original=True) plt.gca().add_collection(coll) plt.sci(coll) # draw vertex data if vertex_data is not None: vtx = vertices[vertex_inds] if vertex_inds is not None else vertices plt.scatter(vtx[:, 0], vtx[:, 1], c=vertex_data, vmin=vmin, vmax=vmax, s=vertex_size) # draw center data if center_data is not None: cts = centers[center_inds] if center_inds is not None else centers plt.scatter(cts[:, 0], cts[:, 1], c=center_data, vmin=vmin, vmax=vmax, s=vertex_size) if volume_data is not None or center_data is not None or vertex_data is not None: plt.colorbar() if new_figure: plt.show() elif self.dim == 3: if volume_data is not None: raise NotImplementedError cube = np.array([[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.], [0., 0., 0.], [0., 0., 1.], [1., 0., 1.], [1., 0., 0.], [1., 0., 1.], [1., 1., 1.], [1., 1., 0.], [1., 1., 1.], [0., 1., 1.], [0., 1., 0.], [0., 1., 1.], [0., 0., 1.]]) from mpl_toolkits.mplot3d import Axes3D # NOQA import matplotlib.pyplot as plt if new_figure: plt.figure() plt.gca().add_subplot(111, projection='3d') ax = plt.gca() # draw cells for leaf, level in zip(self.vertex_ids, self.levels): size = 1. / 2**level ll = self.vertices[leaf[0]] * self.dimensions + self.ranges[:, 0] c = cube * self.dimensions * size + ll ax.plot3D(c[:, 0], c[:, 1], c[:, 2], color='lightgray', zorder=-1) p = None # draw vertex data if vertex_data is not None: vtx = vertices[vertex_inds] if vertex_inds is not None else vertices p = ax.scatter(vtx[:, 0], vtx[:, 1], vtx[:, 2], c=vertex_data, vmin=vmin, vmax=vmax, s=vertex_size) # draw center data if center_data is not None: cts = centers[center_inds] if center_inds is not None else centers p = ax.scatter(cts[:, 0], cts[:, 1], cts[:, 2], c=center_data, vmin=vmin, vmax=vmax, s=vertex_size) if p is not None: plt.colorbar(p) if new_figure: plt.show() else: assert False
def plot(self, gamma=None, annotate=True, axes=None, **imshow_args): """ Plots the map object using matplotlib, in a method equivalent to plt.imshow() using nearest neighbour interpolation. Parameters ---------- gamma : float Gamma value to use for the color map annotate : bool If true, the data is plotted at it's natural scale; with title and axis labels. axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. **imshow_args : dict Any additional imshow arguments that should be used when plotting the image. Examples -------- #Simple Plot with color bar plt.figure() aiamap.plot() plt.colorbar() #Add a limb line and grid aia.plot() aia.draw_limb() aia.draw_grid() """ # Check that the image is properly oriented if not np.array_equal(self.rotation_matrix, np.matrix(np.identity(2))): warnings.warn("This map is not properly oriented. Plot axes may be incorrect", Warning) #Get current axes if not axes: axes = plt.gca() # Normal plot if annotate: axes.set_title("{name} {date:{tmf}}".format(name=self.name, date=parse_time(self.date), tmf=TIME_FORMAT)) # x-axis label if self.coordinate_system['x'] == 'HG': xlabel = 'Longitude [{lon}]'.format(lon=self.units['x']) else: xlabel = 'X-position [{xpos}]'.format(xpos=self.units['x']) # y-axis label if self.coordinate_system['y'] == 'HG': ylabel = 'Latitude [{lat}]'.format(lat=self.units['y']) else: ylabel = 'Y-position [{ypos}]'.format(ypos=self.units['y']) axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) # Determine extent extent = self.xrange + self.yrange cmap = deepcopy(self.cmap) if gamma is not None: cmap.set_gamma(gamma) # make imshow kwargs a dict kwargs = {'origin':'lower', 'cmap':cmap, 'norm':self.mpl_color_normalizer, 'extent':extent, 'interpolation':'nearest'} kwargs.update(imshow_args) ret = axes.imshow(self.data, **kwargs) #Set current image (makes colorbar work) plt.sci(ret) return ret
def ax_scalp(v, channels, ax=None, annotate=False, vmin=None, vmax=None, colormap=None): """Draw a scalp plot. Draws a scalp plot on an existing axes. The method takes an array of values and an array of the corresponding channel names. It matches the channel names with an internal list of known channels and their positions to project them correctly on the scalp. .. warning:: The behaviour for unkown channels is undefined. Parameters ---------- v : 1d-array of floats The values for the channels channels : 1d array of strings The corresponding channel names for the values in ``v`` ax : Axes, optional The axes to draw the scalp plot on. If not provided, the currently activated axes (i.e. ``gca()``) will be taken annotate : Boolean, optional Draw the channel names next to the channel markers. vmin, vmax : float, optional The display limits for the values in ``v``. If the data in ``v`` contains values between -3..3 and ``vmin`` and ``vmax`` are set to -1 and 1, all values smaller than -1 and bigger than 1 will appear the same as -1 and 1. If not set, the maximum absolute value in ``v`` is taken to calculate both values. colormap : matplotlib.colors.colormap, optional A colormap to define the color transitions. Returns ------- ax : Axes the axes on which the plot was drawn See Also -------- ax_colorbar """ if ax is None: ax = plt.gca() # what if we have an unknown channel? points = [get_channelpos(c) for c in channels] # calculate the interpolation x = [i[0] for i in points] y = [i[1] for i in points] z = v # interplolate the in-between values xx = np.linspace(min(x), max(x), 500) yy = np.linspace(min(y), max(y), 500) xx, yy = np.meshgrid(xx, yy) f = interpolate.LinearNDInterpolator(list(zip(x, y)), z) zz = f(xx, yy) # draw the contour map ctr = ax.contourf(xx, yy, zz, 20, vmin=vmin, vmax=vmax, cmap=colormap) ax.contour(xx, yy, zz, 5, colors="k", vmin=vmin, vmax=vmax, linewidths=.1) # paint the head ax.add_artist(plt.Circle((0, 0), 1, linestyle='solid', linewidth=2, fill=False)) # add a nose ax.plot([-0.1, 0, 0.1], [1, 1.1, 1], 'k-') # add markers at channels positions ax.plot(x, y, 'k+') # set the axes limits, so the figure is centered on the scalp ax.set_ylim([-1.05, 1.15]) ax.set_xlim([-1.15, 1.15]) # hide the frame and axes # hiding the axes might be too much, as this will also hide the x/y # labels :/ ax.set_frame_on(False) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # draw the channel names if annotate: for i in zip(channels, list(zip(x, y))): ax.annotate(" " + i[0], i[1]) ax.set_aspect(1) plt.sci(ctr) return ax
def plot(self, axes=None, annotate=True, # pylint: disable=W0613 title="SunPy Composite Plot", **matplot_args): """Plots the composite map object using matplotlib Parameters ---------- axes: `~matplotlib.axes.Axes` or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. annotate : `bool` If true, the data is plotted at it's natural scale; with title and axis labels. title : `str` Title of the composite map. **matplot_args : `dict` Matplotlib Any additional imshow arguments that should be used when plotting. Returns ------- ret : `list` List of axes image or quad contour sets that have been plotted. """ # Get current axes if not axes: axes = plt.gca() if annotate: axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0], self._maps[0].spatial_units[0])) axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1], self._maps[0].spatial_units[1])) axes.set_title(title) # Define a list of plotted objects ret = [] # Plot layers of composite map for m in self._maps: # Parameters for plotting params = { "origin": "lower", "extent": list(m.xrange.value) + list(m.yrange.value), "cmap": m.plot_settings['cmap'], "norm": m.plot_settings['norm'], "alpha": m.alpha, "zorder": m.zorder, } params.update(matplot_args) if m.levels is False: ret.append(axes.imshow(m.data, **params)) # Use contour for contour data, and imshow otherwise if m.levels is not False: # Set data with values <= 0 to transparent # contour_data = np.ma.masked_array(m, mask=(m <= 0)) ret.append(axes.contour(m.data, m.levels, **params)) # Set the label of the first line so a legend can be created ret[-1].collections[0].set_label(m.name) # Adjust axes extents to include all data axes.axis('image') # Set current image (makes colorbar work) plt.sci(ret[0]) return ret
def specshow(data, x_coords=None, y_coords=None, x_axis=None, y_axis=None, sr=48000, hop_length=512, fmin=None, fmax=None, bins_per_octave=12, **kwargs): '''Display a spectrogram/chromagram/cqt/etc. Parameters ---------- data : np.ndarray [shape=(d, n)] Matrix to display (e.g., spectrogram) sr : number > 0 [scalar] Sample rate used to determine time scale in x-axis. hop_length : int > 0 [scalar] Hop length, also used to determine time scale in x-axis x_axis : None or str y_axis : None or str Range for the x- and y-axes. Valid types are: - None, 'none', or 'off' : no axis decoration is displayed. Frequency types: - 'linear', 'fft', 'hz' : frequency range is determined by the FFT window and sampling rate. - 'log' : the spectrum is displayed on a log scale. - 'mel' : frequencies are determined by the mel scale. - 'cqt_hz' : frequencies are determined by the CQT scale. - 'cqt_note' : pitches are determined by the CQT scale. All frequency types are plotted in units of Hz. Categorical types: - 'chroma' : pitches are determined by the chroma filters. Pitch classes are arranged at integer locations (0-11). - 'tonnetz' : axes are labeled by Tonnetz dimensions (0-5) - 'frames' : markers are shown as frame counts. Time types: - 'time' : markers are shown as milliseconds, seconds, minutes, or hours - 'lag' : like time, but past the half-way point counts as negative values. All time types are plotted in units of seconds. Other: - 'tempo' : markers are shown as beats-per-minute (BPM) using a logarithmic scale. x_coords : np.ndarray [shape=data.shape[1]+1] y_coords : np.ndarray [shape=data.shape[0]+1] Optional positioning coordinates of the input data. These can be use to explicitly set the location of each element `data[i, j]`, e.g., for displaying beat-synchronous features in natural time coordinates. If not provided, they are inferred from `x_axis` and `y_axis`. fmin : float > 0 [scalar] or None Frequency of the lowest spectrogram bin. Used for Mel and CQT scales. If `y_axis` is `cqt_hz` or `cqt_note` and `fmin` is not given, it is set by default to `note_to_hz('C1')`. fmax : float > 0 [scalar] or None Used for setting the Mel frequency scales bins_per_octave : int > 0 [scalar] Number of bins per octave. Used for CQT frequency scale. kwargs : additional keyword arguments Arguments passed through to `matplotlib.pyplot.pcolormesh`. By default, the following options are set: - `rasterized=True` - `shading='flat'` - `edgecolors='None'` Returns ------- axes The axis handle for the figure. See Also -------- cmap : Automatic colormap detection matplotlib.pyplot.pcolormesh Examples -------- Visualize an STFT power spectrum >>> import matplotlib.pyplot as plt >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> plt.figure(figsize=(12, 8)) >>> D = librosa.amplitude_to_db(librosa.stft(y), ref=np.max) >>> plt.subplot(4, 2, 1) >>> librosa.display.specshow(D, y_axis='linear') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Linear-frequency power spectrogram') Or on a logarithmic scale >>> plt.subplot(4, 2, 2) >>> librosa.display.specshow(D, y_axis='log') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Log-frequency power spectrogram') Or use a CQT scale >>> CQT = librosa.amplitude_to_db(librosa.cqt(y, sr=sr), ref=np.max) >>> plt.subplot(4, 2, 3) >>> librosa.display.specshow(CQT, y_axis='cqt_note') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Constant-Q power spectrogram (note)') >>> plt.subplot(4, 2, 4) >>> librosa.display.specshow(CQT, y_axis='cqt_hz') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Constant-Q power spectrogram (Hz)') Draw a chromagram with pitch classes >>> C = librosa.feature.chroma_cqt(y=y, sr=sr) >>> plt.subplot(4, 2, 5) >>> librosa.display.specshow(C, y_axis='chroma') >>> plt.colorbar() >>> plt.title('Chromagram') Force a grayscale colormap (white -> black) >>> plt.subplot(4, 2, 6) >>> librosa.display.specshow(D, cmap='gray_r', y_axis='linear') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Linear power spectrogram (grayscale)') Draw time markers automatically >>> plt.subplot(4, 2, 7) >>> librosa.display.specshow(D, x_axis='time', y_axis='log') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Log power spectrogram') Draw a tempogram with BPM markers >>> plt.subplot(4, 2, 8) >>> Tgram = librosa.feature.tempogram(y=y, sr=sr) >>> librosa.display.specshow(Tgram, x_axis='time', y_axis='tempo') >>> plt.colorbar() >>> plt.title('Tempogram') >>> plt.tight_layout() Draw beat-synchronous chroma in natural time >>> plt.figure() >>> tempo, beat_f = librosa.beat.beat_track(y=y, sr=sr, trim=False) >>> beat_f = librosa.util.fix_frames(beat_f, x_max=C.shape[1]) >>> Csync = librosa.util.sync(C, beat_f, aggregate=np.median) >>> beat_t = librosa.frames_to_time(beat_f, sr=sr) >>> ax1 = plt.subplot(2,1,1) >>> librosa.display.specshow(C, y_axis='chroma', x_axis='time') >>> plt.title('Chroma (linear time)') >>> ax2 = plt.subplot(2,1,2, sharex=ax1) >>> librosa.display.specshow(Csync, y_axis='chroma', x_axis='time', ... x_coords=beat_t) >>> plt.title('Chroma (beat time)') >>> plt.tight_layout() ''' if np.issubdtype(data.dtype, np.complex128): warnings.warn('Trying to display complex-valued input. ' 'Showing magnitude instead.') data = np.abs(data) kwargs.setdefault('cmap', cmap(data)) kwargs.setdefault('rasterized', True) kwargs.setdefault('edgecolors', 'None') kwargs.setdefault('shading', 'flat') all_params = dict(kwargs=kwargs, sr=sr, fmin=fmin, fmax=fmax, bins_per_octave=bins_per_octave, hop_length=hop_length) # Get the x and y coordinates y_coords = __mesh_coords(y_axis, y_coords, data.shape[0], **all_params) x_coords = __mesh_coords(x_axis, x_coords, data.shape[1], **all_params) axes = plt.gca() out = axes.pcolormesh(x_coords, y_coords, data, **kwargs) plt.sci(out) axes.set_xlim(x_coords.min(), x_coords.max()) axes.set_ylim(y_coords.min(), y_coords.max()) # Set up axis scaling __scale_axes(axes, x_axis, 'x') __scale_axes(axes, y_axis, 'y') # Construct tickers and locators __decorate_axis(axes.xaxis, x_axis) __decorate_axis(axes.yaxis, y_axis) return axes
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs): """Make a scatter plot of circles. Similar to plt.scatter, but the size of circles are in data scale Parameters ---------- x, y : scalar or array_like, shape (n, ) Input data s : scalar or array_like, shape (n, ) Radius of circles. c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- paths : `~matplotlib.collections.PathCollection` Examples -------- >>> a = np.arange(11) >>> circles(a, a, s=a*0.2, c=a, alpha=0.5, ec='none') >>> plt.colorbar() References ---------- With thanks to https://gist.github.com/syrte/592a062c562cd2a98a83 """ import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.collections import PatchCollection if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) # You can set `facecolor` with an array for each patch, # while you can only set `facecolors` with a value for all. patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)] collection = PatchCollection(patches, **kwargs) if c is not None: collection.set_array(np.asarray(c)) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() plt.draw_if_interactive() if c is not None: plt.sci(collection) return collection
def generateVoltChart(tree, rawOut, modelDir, neatoLayout=True): ''' Map the voltages on a feeder over time using a movie.''' # We need to timestamp frames with the system clock to make sure the browser caches them appropriately. genTime = str(datetime.datetime.now()).replace(':','.') # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob)==dict and ob.get('bustype','')=='SWING': feedVoltage = float(ob.get('nominal_voltage',1)) # Make a graph object. fGraph = feeder.treeToNxGraph(tree) if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) positions = graphviz_layout(cleanG, prog='neato') else: rawPositions = {n:fGraph.node[n].get('pos',(0,0)) for n in fGraph} #HACK: the import code reverses the y coords. def yFlip(pair): try: return (pair[0], -1.0*pair[1]) except: return (0,0) positions = {k:yFlip(rawPositions[k]) for k in rawPositions} # Plot all time steps. nodeVolts = {} for step, stamp in enumerate(rawOut['aVoltDump.csv']['# timestamp']): # Build voltage map. nodeVolts[step] = {} for nodeName in [x for x in rawOut['aVoltDump.csv'].keys() if x != '# timestamp']: allVolts = [] for phase in ['a','b','c']: voltStep = rawOut[phase + 'VoltDump.csv'][nodeName][step] # HACK: Gridlab complex number format sometimes uses i, sometimes j, sometimes d. WTF? if type(voltStep) is str: voltStep = voltStep.replace('i','j') v = complex(voltStep) phaseVolt = abs(v) if phaseVolt != 0.0: if _digits(phaseVolt)>3: # Normalize to 120 V standard phaseVolt = phaseVolt*(120/feedVoltage) allVolts.append(phaseVolt) # HACK: Take average of all phases to collapse dimensionality. nodeVolts[step][nodeName] = avg(allVolts) # Draw animation. voltChart = plt.figure(figsize=(15,15)) plt.axes(frameon = 0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(0.0,'blue'),(0.25,'darkgray'),(0.75,'darkgray'),(1.0,'yellow')]) edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes(fGraph, pos = positions, node_color = [nodeVolts[0].get(n,0) for n in fGraph.nodes()], linewidths = 0, node_size = 30, cmap = custom_cm) plt.sci(nodeIm) plt.clim(110,130) plt.colorbar() plt.title(rawOut['aVoltDump.csv']['# timestamp'][0]) def update(step): nodeColors = np.array([nodeVolts[step].get(n,0) for n in fGraph.nodes()]) plt.title(rawOut['aVoltDump.csv']['# timestamp'][step]) nodeIm.set_array(nodeColors) return nodeColors, anim = FuncAnimation(voltChart, update, frames=len(rawOut['aVoltDump.csv']['# timestamp']), interval=200, blit=False) anim.save(pJoin(modelDir,'voltageChart.mp4'), codec='h264', extra_args=['-pix_fmt', 'yuv420p']) # Reclaim memory by closing, deleting and garbage collecting the last chart. voltChart.clf() plt.close() del voltChart gc.collect() return genTime
def plot(self, log = True, zoom = False, sky = True, axes=None, **imshow_args): """ Plots the pyas object using matplotlib, in a method equivalent to plt.imshow(). Overlays information. Parameters ---------- log : bool (default True) Use logarithmic scaling zoom : bool (default False) Show only area around the Sun, not entire pixel array sky : bool (default False) Use sky coordinates instead of pixel coordinates (not yet implemented) axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. **imshow_args : dict Any additional imshow arguments that should be used when plotting the image. """ #Get current axes if not axes: axes = plt.gca() axes.set_title(self.__repr__()) axes.set_ylabel('pixels') axes.set_xlabel('pixels') if zoom is False: xrange = [0,self.data[0,:].size] yrange = [0,self.data[:,0].size] else: xrange = zoom * [self.sun_center[0] - 110, self.sun_center[0] + 110] + self.offset[0] yrange = zoom * [self.sun_center[1] - 110, self.sun_center[1] + 110] + self.offset[1] axes.set_xlim(xrange[0], xrange[1]) axes.set_ylim(yrange[0], yrange[1]) if log: ret = axes.imshow(self.data, cmap=plt.cm.bone, norm = LogNorm()) else: ret = axes.imshow(self.data, cmap=plt.cm.bone) axes.plot(self.fiducials[:,0] + self.offset[0], self.fiducials[:,1] + self.offset[1], "b+") for i in np.arange(0, self.fiducials[:,0].size): if self.fiducials[i,0] != 0 and self.fiducials[i,1] != 0: axes.text(self.fiducials[i,0] + self.offset[0], self.fiducials[i,1] + self.offset[1], self._fiducials_idtext[i], color = "blue") axes.plot(self.sun_center[0] + self.offset[0], self.sun_center[1] + self.offset[1], "r+", markersize = 20) axes.plot(self.limbs[:,0] + self.offset[0], self.limbs[:,1] + self.offset[1], "w+", markersize = 15) plt.colorbar(ret) #plot a cross at the screen center axes.plot(self.screen_center[0] + self.offset[0], self.screen_center[1] + self.offset[1], "b+", markersize = 20) # plot a circle representing the screen c = mpatches.Circle(self.screen_center + self.offset, self.screen_radius, color='b', fill = False, lw = 3) axes.add_patch(c) plt.sci(ret) return ret
def plot(self, axes=None, gamma=None, annotate=True, # pylint: disable=W0613 title="SunPy Composite Plot", **matplot_args): """Plots the composite map object using matplotlib Parameters ---------- axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. gamma : float Gamma value to use for the color map annotate : bool If true, the data is plotted at it's natural scale; with title and axis labels. **matplot_args : dict Matplotlib Any additional imshow arguments that should be used when plotting the image. Returns ------- ret : List List of axes image or quad contour sets that have been plotted. """ #Get current axes if not axes: axes = plt.gca() if annotate: # x-axis label if self._maps[0].coordinate_system['x'] == 'HG': xlabel = 'Longitude [{lon}]'.format(lon=self._maps[0].units['x']) else: xlabel = 'X-position [{solx}]'.format(solx=self._maps[0].units['x']) # y-axis label if self._maps[0].coordinate_system['y'] == 'HG': ylabel = 'Latitude [{lat}]'.format(lat=self._maps[0].units['y']) else: ylabel = 'Y-position [{soly}]'.format(soly=self._maps[0].units['y']) axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) axes.set_title(title) #Define a list of plotted objects ret = [] # Plot layers of composite map for m in self._maps: # Parameters for plotting params = { "origin": "lower", "extent": m.xrange + m.yrange, "cmap": m.cmap, "norm": m.mpl_color_normalizer, "alpha": m.alpha, "zorder": m.zorder, } params.update(matplot_args) if m.levels is False: ret.append(axes.imshow(m.data, **params)) # Use contour for contour data, and imshow otherwise if m.levels is not False: # Set data with values <= 0 to transparent # contour_data = np.ma.masked_array(m, mask=(m <= 0)) ret.append(axes.contour(m.data, m.levels, **params)) #Set the label of the first line so a legend can be created ret[-1].collections[0].set_label(m.name) # Adjust axes extents to include all data axes.axis('image') #Set current image (makes colorbar work) plt.sci(ret[0]) return ret
def plot(self, axes=None, gamma=None, annotate=True, # pylint: disable=W0613 title="SunPy Composite Plot", **matplot_args): """Plots the composite map object using matplotlib Parameters ---------- axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. gamma : float Gamma value to use for the color map annotate : bool If true, the data is plotted at it's natural scale; with title and axis labels. **matplot_args : dict Matplotlib Any additional imshow arguments that should be used when plotting the image. Returns ------- ret : List List of axes image or quad contour sets that have been plotted. """ #Get current axes if not axes: axes = plt.gca() if annotate: # x-axis label if self._maps[0].coordinate_system['x'] == 'HG': xlabel = 'Longitude [%s]' % self._maps[0].units['x'] else: xlabel = 'X-position [%s]' % self._maps[0].units['x'] # y-axis label if self._maps[0].coordinate_system['y'] == 'HG': ylabel = 'Latitude [%s]' % self._maps[0].units['y'] else: ylabel = 'Y-position [%s]' % self._maps[0].units['y'] axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) axes.set_title(title) #Define a list of plotted objects ret = [] # Plot layers of composite map for m in self._maps: # Parameters for plotting params = { "origin": "lower", "extent": m.xrange + m.yrange, "cmap": m.cmap, "norm": m.norm(), "alpha": m.alpha, "zorder": m.zorder, } params.update(matplot_args) if m.levels is False: ret.append(axes.imshow(m, **params)) # Use contour for contour data, and imshow otherwise if m.levels is not False: # Set data with values <= 0 to transparent # contour_data = np.ma.masked_array(m, mask=(m <= 0)) ret.append(axes.contour(m, m.levels, **params)) #Set the label of the first line so a legend can be created ret[-1].collections[0].set_label(m.name) # Adjust axes extents to include all data axes.axis('image') #Set current image (makes colorbar work) plt.sci(ret[0]) return ret
# simple example showing how it is done. N = 50 x = np.arange(N) # Here are many sets of y to plot vs x ys = [x + i for i in x] # We need to set the plot limits, they will not autoscale fig, ax = plt.subplots() ax.set_xlim(np.min(x), np.max(x)) ax.set_ylim(np.min(ys), np.max(ys)) # colors is sequence of rgba tuples # linestyle is a string or dash tuple. Legal string values are # solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) # where onoffseq is an even length tuple of on and off ink in points. # If linestyle is omitted, 'solid' is used # See :class:`matplotlib.collections.LineCollection` for more information # Make a sequence of x,y pairs line_segments = LineCollection([np.column_stack([x, y]) for y in ys], linewidths=(0.5, 1, 1.5, 2), linestyles='solid') line_segments.set_array(x) ax.add_collection(line_segments) axcb = fig.colorbar(line_segments) axcb.set_label('Line Number') ax.set_title('Line Collection with mapped colors') plt.sci(line_segments) # This allows interactive changing of the colormap. plt.show()
def plot(self, gamma=None, annotate=True, axes=None, **imshow_args): """ Plots the map object using matplotlib, in a method equivalent to plt.imshow() using nearest neighbour interpolation. Parameters ---------- gamma : float Gamma value to use for the color map annotate : bool If true, the data is plotted at it's natural scale; with title and axis labels. axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. **imshow_args : dict Any additional imshow arguments that should be used when plotting the image. Examples -------- #Simple Plot with color bar plt.figure() aiamap.plot() plt.colorbar() #Add a limb line and grid aia.plot() aia.draw_limb() aia.draw_grid() """ # Check that the image is properly aligned if not np.array_equal(self.rotation_matrix, np.matrix(np.identity(2))): warnings.warn("This map is not aligned. Plot axes may be incorrect", Warning) # Get current axes if not axes: axes = plt.gca() # Normal plot if annotate: axes.set_title("%s %s" % (self.name, parse_time(self.date).strftime("%Y-%m-%d %H:%M:%S.%f"))) # x-axis label if self.coordinate_system["x"] == "HG": xlabel = "Longitude [%s]" % self.units["x"] else: xlabel = "X-position [%s]" % self.units["x"] # y-axis label if self.coordinate_system["y"] == "HG": ylabel = "Latitude [%s]" % self.units["y"] else: ylabel = "Y-position [%s]" % self.units["y"] axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) # Determine extent extent = self.xrange + self.yrange cmap = deepcopy(self.cmap) if gamma is not None: cmap.set_gamma(gamma) # make imshow kwargs a dict kwargs = { "origin": "lower", "cmap": cmap, "norm": self.mpl_color_normalizer, "extent": extent, "interpolation": "nearest", } kwargs.update(imshow_args) ret = axes.imshow(self.data, **kwargs) # Set current image (makes colorbar work) plt.sci(ret) return ret
node_color_map=cm.get_cmap('gist_yarg') edge_color_map=cm.get_cmap('jet') nx.draw(G,pos=pos_vals, alpha=0.07, with_labels=False) nx.draw_networkx_nodes(sample, pos_vals, nodelist=sample.graph['source_nodes'], alpha=0.7, node_shape='s', node_size=600, node_color='chocolate') nx.draw_networkx_nodes(sample, pos_vals, nodelist=sample.graph['destination_nodes'],alpha=0.7, node_shape='s', node_size=600, node_color='#87CEFA') nodes=nx.draw_networkx_nodes(sample, pos_vals, nodelist=sample.nodes(), node_color=n_color, cmap=node_color_map, vmin=min(n_color), vmax=max(n_color)) edges=nx.draw_networkx_edges(G, pos_vals, edgelist=sample.edges(),width=2, edge_color=e_color, edge_cmap=edge_color_map, edge_vmin=min(e_color),edge_vmax=max(e_color)) for n in sample.nodes(): x,y=pos_vals[n] plt.text(x,y-0.005,s=str(n)+'-'+str(sample.node[n]['times_selected']),horizontalalignment='center', fontdict={'color' : 'darkred','weight' : 'bold', 'size' : 12}) if min(n_color) != max(n_color): plt.sci(nodes) res=np.linspace(min(n_color), max(n_color), 10) cb=plt.colorbar(shrink=.7) print len(res) , res[1], res[0] if max(n_color)-min(n_color)< 10 or res[1]-res[0]< 1: cb.locator=MultipleLocator(1) cb.update_ticks() cb.set_label("Node degree") if min(e_color) != max(e_color): plt.sci(edges) res=np.linspace(min(e_color), max(e_color), 10) cb=plt.colorbar(orientation='horizontal' , shrink=.7) if max(e_color)-min(e_color)< 10 or res[1]-res[0]< 1: cb.locator=MultipleLocator(1) cb.update_ticks()
def plot(self, axes=None, annotate=True, # pylint: disable=W0613 title="SunPy Composite Plot", **matplot_args): """Plots the composite map object using matplotlib Parameters ---------- axes: `~matplotlib.axes.Axes` or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. annotate : `bool` If true, the data is plotted at it's natural scale; with title and axis labels. title : `str` Title of the composite map. **matplot_args : `dict` Matplotlib Any additional imshow arguments that should be used when plotting. Returns ------- ret : `list` List of axes image or quad contour sets that have been plotted. """ # Get current axes if not axes: axes = plt.gca() if annotate: axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0], self._maps[0].spatial_units[0])) axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1], self._maps[0].spatial_units[1])) axes.set_title(title) # Define a list of plotted objects ret = [] # Plot layers of composite map for m in self._maps: # Parameters for plotting bl = m._get_lon_lat(m.bottom_left_coord) tr = m._get_lon_lat(m.top_right_coord) x_range = list(u.Quantity([bl[0], tr[0]]).to(m.spatial_units[0]).value) y_range = list(u.Quantity([bl[1], tr[1]]).to(m.spatial_units[1]).value) params = { "origin": "lower", "extent": x_range + y_range, "cmap": m.plot_settings['cmap'], "norm": m.plot_settings['norm'], "alpha": m.alpha, "zorder": m.zorder, } params.update(matplot_args) # The request to show a map layer rendered as a contour is indicated by a # non False levels property. If levels is False, then the layer is # rendered using imshow. if m.levels is False: # Check for the presence of masked map data if m.mask is None: ret.append(axes.imshow(m.data, **params)) else: ret.append(axes.imshow(np.ma.array(np.asarray(m.data), mask=m.mask), **params)) else: # Check for the presence of masked map data if m.mask is None: ret.append(axes.contour(m.data, m.levels, **params)) else: ret.append(axes.contour(np.ma.array(np.asarray(m.data), mask=m.mask), m.levels, **params)) # Set the label of the first line so a legend can be created ret[-1].collections[0].set_label(m.name) # Adjust axes extents to include all data axes.axis('image') # Set current image (makes colorbar work) plt.sci(ret[0]) return ret
def generateVoltChart(tree, rawOut, modelDir, neatoLayout=True): ''' Map the voltages on a feeder over time using a movie.''' # We need to timestamp frames with the system clock to make sure the browser caches them appropriately. genTime = str(datetime.datetime.now()).replace(':','.') # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob)==dict and ob.get('bustype','')=='SWING': feedVoltage = float(ob.get('nominal_voltage',1)) # Make a graph object. fGraph = feeder.treeToNxGraph(tree) if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) # was formerly : positions = nx.graphviz_layout(cleanG, prog='neato') but this threw an error positions = graphviz_layout(cleanG, prog='neato') else: rawPositions = {n:fGraph.node[n].get('pos',(0,0)) for n in fGraph} #HACK: the import code reverses the y coords. def yFlip(pair): try: return (pair[0], -1.0*pair[1]) except: return (0,0) positions = {k:yFlip(rawPositions[k]) for k in rawPositions} # Plot all time steps. nodeVolts = {} for step, stamp in enumerate(rawOut['aVoltDump.csv']['# timestamp']): # Build voltage map. nodeVolts[step] = {} for nodeName in [x for x in rawOut['aVoltDump.csv'].keys() if x != '# timestamp']: allVolts = [] for phase in ['a','b','c']: voltStep = rawOut[phase + 'VoltDump.csv'][nodeName][step] # HACK: Gridlab complex number format sometimes uses i, sometimes j, sometimes d. WTF? if type(voltStep) is str: voltStep = voltStep.replace('i','j') v = complex(voltStep) phaseVolt = abs(v) if phaseVolt != 0.0: if _digits(phaseVolt)>3: # Normalize to 120 V standard phaseVolt = phaseVolt*(120/feedVoltage) allVolts.append(phaseVolt) # HACK: Take average of all phases to collapse dimensionality. nodeVolts[step][nodeName] = avg(allVolts) # Draw animation. voltChart = plt.figure(figsize=(15,15)) plt.axes(frameon = 0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(0.0,'blue'),(0.25,'darkgray'),(0.75,'darkgray'),(1.0,'yellow')]) edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes(fGraph, pos = positions, node_color = [nodeVolts[0].get(n,0) for n in fGraph.nodes()], linewidths = 0, node_size = 30, cmap = custom_cm) plt.sci(nodeIm) plt.clim(110,130) plt.colorbar() plt.title(rawOut['aVoltDump.csv']['# timestamp'][0]) def update(step): nodeColors = np.array([nodeVolts[step].get(n,0) for n in fGraph.nodes()]) plt.title(rawOut['aVoltDump.csv']['# timestamp'][step]) nodeIm.set_array(nodeColors) return nodeColors, anim = FuncAnimation(voltChart, update, frames=len(rawOut['aVoltDump.csv']['# timestamp']), interval=200, blit=False) anim.save(pJoin(modelDir,'voltageChart.mp4'), codec='h264', extra_args=['-pix_fmt', 'yuv420p']) # Reclaim memory by closing, deleting and garbage collecting the last chart. voltChart.clf() plt.close() del voltChart gc.collect() return genTime
def plot(self, gamma=None, annotate=True, axes=None, controls=False, interval=200, resample=False, colorbar=False, ani_args={}, **imshow_args): """ A animation plotting routine that animates each element in the MapCube Parameters ---------- gamma: float Gamma value to use for the color map annotate: bool If true, the data is plotted at it's natural scale; with title and axis labels. axes: matplotlib.axes object or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. controls: bool Adds play / pause button to the animation interval: int Frame display time in ms. resample: list or False Draws the map at a lower resolution to increase the speed of animation. Specify a list as a fraction i.e. [0.25, 0.25] to plot at 1/4 resolution. colorbar: bool Draw a colorbar on the plot. ani_args : dict Passed to sunpy.util.plotting.ControlFuncAnimation imshow_args: dict Any additional imshow arguments that should be used when plotting the image. Examples -------- >>> cube = sunpy.Map(files, cube=True) >>> ani = cube.plot(colorbar=True) >>> plt.show() Plot the map at 1/2 original resolution >>> cube = sunpy.Map(files, cube=True) >>> ani = cube.plot(resample=[0.5, 0.5], colorbar=True) >>> plt.show() Save an animation of the MapCube >>> cube = sunpy.Map(res, cube=True) >>> ani = cube.plot(controls=False) >>> Writer = animation.writers['ffmpeg'] >>> writer = Writer(fps=10, metadata=dict(artist='SunPy'), bitrate=1800) >>> ani.save('mapcube_animation.mp4', writer=writer) """ if not axes: axes = plt.gca() fig = axes.get_figure() # Normal plot if annotate: axes.set_title("%s %s" % (self[0].name, self[0].date)) # x-axis label if self[0].coordinate_system['x'] == 'HG': xlabel = 'Longitude [%s]' % self[0].units['x'] else: xlabel = 'X-position [%s]' % self[0].units['x'] # y-axis label if self[0].coordinate_system['y'] == 'HG': ylabel = 'Latitude [%s]' % self[0].units['y'] else: ylabel = 'Y-position [%s]' % self[0].units['y'] axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) # Determine extent extent = self[0].xrange + self[0].yrange cmap = copy(self[0].cmap) if gamma is not None: cmap.set_gamma(gamma) #make imshow kwargs a dict kwargs = {'origin':'lower', 'cmap':cmap, 'norm':self[0].norm, 'extent':extent, 'interpolation':'nearest'} kwargs.update(imshow_args) im = axes.imshow(self[0].data, **kwargs) #Set current image (makes colorbar work) plt.sci(im) divider = make_axes_locatable(axes) cax = divider.append_axes("right", size="5%", pad=0.2) cbar = plt.colorbar(im,cax) if resample: #This assumes that the maps a homogenous! #TODO: Update this! resample = np.array(len(self._maps)-1) * np.array(resample) ani_data = [x.resample(resample) for x in self] else: ani_data = self def updatefig(i, *args): im = args[0] im.set_array(args[2][i].data) im.set_cmap(self[i].cmap) im.set_norm(self[i].norm) if args[1]: axes.set_title("%s %s" % (self[i].name, self[i].date)) ani = plotting.ControlFuncAnimation(fig, updatefig, frames=xrange(0,len(self._maps)), fargs=[im,annotate,ani_data], interval=interval, blit=False) if controls: axes, bax1, bax2, bax3 = plotting.add_controls(axes=axes) bax1._button.on_clicked(ani._start) bax2._button.on_clicked(ani._stop) bax3._button.on_clicked(ani._step) return ani
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs): """ Make a scatter of circles plot of x vs y, where x and y are sequence like objects of the same lengths. The size of circles are in data scale. Parameters ---------- x,y : scalar or array_like, shape (n, ) Input data s : scalar or array_like, shape (n, ) Radius of circle in data unit. c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- paths : `~matplotlib.collections.PathCollection` Examples -------- a = np.arange(11) circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none') plt.colorbar() License -------- This code is under [The BSD 3-Clause License] (http://opensource.org/licenses/BSD-3-Clause) """ from matplotlib.patches import Circle from matplotlib.collections import PatchCollection if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)] collection = PatchCollection(patches, **kwargs) if c is not None: collection.set_array(np.asarray(c)) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() if c is not None: plt.sci(collection) return collection
width=4, edge_color='chocolate', alpha=0.7, ) if len(n_color) > 0: nodes = nx.draw_networkx_nodes(sample, pos_vals, nodelist=sample.nodes(), node_color=n_color, cmap=node_color_map, vmin=min(n_color), vmax=max(n_color), with_labels=False) if min(n_color) != max(n_color): plt.sci(nodes) res = np.linspace(min(n_color), max(n_color), 10) cb = plt.colorbar(shrink=.7) if max(n_color) - min(n_color) < 10 or res[1] - res[0] < 1: cb.locator = MultipleLocator(1) cb.update_ticks() cb.set_label("Node degree") if len(e_color) > 0: edges = nx.draw_networkx_edges(G, pos_vals, edgelist=sample.edges(), width=2, edge_color=e_color, edge_cmap=edge_color_map, edge_vmin=min(e_color),
import numpy as np import matplotlib.pyplot as plt import matplotlib.axes as ax plt.plot() plt.scatter(x, y, s, m) plt.sci(x) plt.semilogy() plt.scatter(1, 3, 4) plt.scatter(1, 2, 3) plt.plot(1, 2) plt.scatter(1, 3) plt.axes(1, 6) plt.scatter() plt.scatter(x, y, z) class some_class(object): """ This is the docstring of this class containing information about its contents : it does nothing ! """ def __init__(self): pass def some_function(): """ This function does nothing """ pass
def plot_figure_05(cells, benchmark_data, cmap=plt.cm.coolwarm, TRANSIENT=500.): '''Plot some traces'n'stuff''' from matplotlib.colors import LogNorm TEMPLATELEN = benchmark_data.TEMPLATELEN f = h5py.File(os.path.join(benchmark_data.savefolder, 'testISIshapes.h5')) amplitudes_raw = f['amplitudes_raw'].value amplitudes_flt = f['amplitudes_flt'].value templatesRaw = f['templatesRaw'].value templatesFlt = f['templatesFlt'].value ISI = f['ISI'].value concAPtemplates = f['APtemplates'].value AP_amplitudes = f['AP_amplitudes'].value AP_widths = f['AP_widths'].value f.close() #sorting array argsort = np.argsort(ISI) #plot some LFP-traces for a single cell fig = plt.figure(figsize=(10, 13)) fig.subplots_adjust(wspace=0.4, hspace=0.3, bottom=0.05, top=0.95, left=0.075, right=0.90) ax = fig.add_subplot(5, 3, 1) #find spikecount in total numspikes = [] for cell in cells.values(): numspikes = np.r_[numspikes, cell.AP_train.sum()] #pick an index with "average" rate cellkey = np.abs(numspikes - numspikes.mean()).argmin() ##plot some PSDs from somav and LFP #choose one cell cell = cells[cellkey] cell.tvec = np.arange(cell.somav.size) * cell.timeres_python inds = np.where((cell.tvec >= TRANSIENT) & (cell.tvec <= TRANSIENT + 500))[0] somav = cell.somav[inds] somav -= somav.min() somav /= somav.max() traces = somav xmins = [] for j in xrange(3): x = cell.LFP[j, inds] xmin = x.min() xmins.append(xmin) x /= -xmin x -= 1.5 * j + 0.5 traces = np.c_[traces, x] #print traces.shape traces = traces.T ax.set_xlim(TRANSIENT, cell.tvec[inds][-1]) ax.set_ylim(traces.min(), traces.max()) line_segments = LineCollection([zip(cell.tvec[inds], x) \ for x in traces], linewidths=(1), colors=('k'), linestyles='solid', rasterized=True, clip_on=False) ax.add_collection(line_segments) #scalebars ax.plot([cell.tvec[inds[-1]], cell.tvec[inds[-1]]], [1, 0], 'k', lw=4, clip_on=False) ax.text(cell.tvec[inds[-1]] * 1.03, 0., r'%.0f' % (cell.somav[inds].max() - cell.somav[inds].min()) + '\n' + 'mV', color='k', fontsize=smallfontsize, va='bottom', ha='left') for j in xrange(3): ax.plot([cell.tvec[inds[-1]], cell.tvec[inds[-1]]], [-j * 1.5 - 0.5, -j * 1.5 - 1.5], 'k', lw=4, clip_on=False) ax.text(cell.tvec[inds[-1]] * 1.03, -j * 1.5 - 1.5, r'%.0f' % (abs(xmins[j] * 1E3)) + '\n' + '$\mu$V', color='k', fontsize=smallfontsize, va='bottom', ha='left') for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top', 'left']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.set_xlabel(r'$t$ (ms)', labelpad=0.1) ax.set_yticks([0.0, -0.5, -2, -3.5]) ax.set_yticklabels([ r'$V_\mathrm{soma}$', r'$\Phi_{x=10}$', r'$\Phi_{x=50}$', r'$\Phi_{x=100}$' ]) ax.axis(ax.axis('tight')) ax.text(-0.2, 1.0, 'a', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) #raise Exception PSDs = np.array([]) #psd of somav psd, freqs = plt.mlab.psd( cell.somav[cell.tvec > TRANSIENT] - cell.somav[cell.tvec > TRANSIENT].mean(), NFFT=2**15 + 2**14, noverlap=int((2**15 + 2**14) * 3. / 4), #5096, Fs=1E3 / np.diff(cell.tvec)[-1]) PSDs = np.r_[PSDs, psd[1:]] #psds of LFPs for j in xrange(3): psd, freqs = plt.mlab.psd( cell.LFP[j, cell.tvec > TRANSIENT] - cell.LFP[j, cell.tvec > TRANSIENT].mean(), NFFT=2**15 + 2**14, noverlap=int((2**15 + 2**14) * 3. / 4), #NFFT=5096, Fs=1E3 / np.diff(cell.tvec)[-1]) PSDs = np.c_[PSDs, psd[1:]] PSDs = PSDs.T #create axes object ax = fig.add_subplot(5, 3, 2) ax.set_xlim(freqs[1], freqs[-1]) ax.set_ylim(PSDs[1:].min(), PSDs[1:].max()) #create line collection line_segments = LineCollection([zip(freqs[1:], x) \ for x in PSDs], linewidths=(1), colors=('k'), linestyles='solid', rasterized=True) ax.add_collection(line_segments) plt.sci(line_segments) # This allows interactive changing of the colormap. ax.loglog() for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlabel(r'$f$ (Hz)', labelpad=0.1) ax.set_title(r'PSD (mV$^2$/Hz)') ax.axis(ax.axis('tight')) ax.grid('on') ax.text(-0.2, 1.0, 'b', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) #plot histogram over ISI ax = fig.add_subplot(5, 3, 3) bins = 10**np.linspace(np.log10(1), np.log10(1E3), 100) ax.hist(ISI, bins=bins, color='gray', histtype='stepfilled', linewidth=0) ax.semilogx() for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.axis(ax.axis('tight')) ax.set_xlim([bins.min(), bins.max()]) ax.set_ylim(bottom=0) ax.set_ylabel('count (-)', labelpad=0) ax.set_xlabel('ISI (ms)', labelpad=0.1) ax.set_title('ISI distr. %i APs' % ISI.size) ax.text(-0.2, 1.0, 'c', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) #plot nonfiltered spike waveforms ax = fig.add_subplot(5, 3, 4) line_segments = LineCollection([zip(np.arange(TEMPLATELEN), x) \ for x in concAPtemplates[argsort, TEMPLATELEN*0:TEMPLATELEN*1]], linewidths=(1), linestyles='solid', norm=LogNorm(), cmap = plt.cm.get_cmap(cmap, 51), rasterized=True) line_segments.set_array(ISI[argsort]) ax.add_collection(line_segments) ax.axis(ax.axis('tight')) for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_ylabel(r'$V_\mathrm{soma}$ (mV)', labelpad=0) ax.set_xlabel('samples (-)', labelpad=0.1) ax.text(-0.2, 1.0, 'd', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) #plot AP amplitudes vs widths ax = fig.add_subplot(5, 3, 5) #mask out invalid widths mask = True - np.isnan(AP_widths) sc = ax.scatter( AP_widths[mask[argsort]], AP_amplitudes[mask[argsort]], marker='o', edgecolors='none', s=5, c=ISI[mask[argsort]], norm=LogNorm(), cmap=plt.cm.get_cmap(cmap, 51), #bins.size) alpha=1, clip_on=False, rasterized=True) ax.set_ylabel('AP ampl. (mV)', labelpad=0) ax.set_xlabel('AP width (ms)', labelpad=0.1) for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlim([AP_widths[mask].min(), AP_widths[mask].max()]) ax.set_ylim([AP_amplitudes[mask].min(), AP_amplitudes[mask].max()]) ax.text(-0.2, 1.0, 'e', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) ax = fig.add_subplot(5, 3, 6) #set lims ax.set_xlim(0, TEMPLATELEN) ax.set_ylim( templatesRaw[np.isfinite(templatesRaw[:, 0]), :][:, TEMPLATELEN * 0:TEMPLATELEN * 1].min(), templatesRaw[np.isfinite(templatesRaw[:, 0]), :][:, TEMPLATELEN * 0:TEMPLATELEN * 1].max()) #create linecollections line_segments = LineCollection([zip(np.arange(TEMPLATELEN), x) \ for x in templatesRaw[argsort, TEMPLATELEN*0:TEMPLATELEN*1]], linewidths=(1), linestyles='solid', norm=LogNorm(), cmap = plt.cm.get_cmap(cmap, 51), rasterized=True) line_segments.set_array(ISI[argsort]) ax.add_collection(line_segments) for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_ylabel(r'$\Phi_{x=10}$ (mV)', labelpad=0) ax.set_xlabel('samples (-)', labelpad=0.1) rect = np.array(ax.get_position().bounds) rect[0] += rect[2] + 0.01 rect[2] = 0.015 cax = fig.add_axes(rect) cax.set_rasterization_zorder(1) axcb = fig.colorbar(line_segments, cax=cax) axcb.ax.set_visible(True) ticks = [5, 10, 20, 50, 100, 200, 500, 1000] axcb.set_ticks(ticks) axcb.set_ticklabels(ticks) axcb.set_label('ISI (ms)', va='center', ha='center', labelpad=0) ax.text(-0.2, 1.0, 'f', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) #plot FILTERED spike waveforms ax = fig.add_subplot(5, 3, 7) #set lims ax.set_xlim(0, TEMPLATELEN) ax.set_ylim( templatesFlt[np.isfinite(templatesFlt[:, 0]), :][:, TEMPLATELEN * 0:TEMPLATELEN * 1].min(), templatesFlt[np.isfinite(templatesFlt[:, 0]), :][:, TEMPLATELEN * 0:TEMPLATELEN * 1].max()) #create linecollections line_segments = LineCollection([zip(np.arange(TEMPLATELEN), x) \ for x in templatesFlt[argsort, TEMPLATELEN*0:TEMPLATELEN*1]], linewidths=(1), linestyles='solid', norm=LogNorm(), cmap = plt.cm.get_cmap(cmap, 51), rasterized=True) line_segments.set_array(ISI[argsort]) ax.add_collection(line_segments) for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlabel('samples (-)', labelpad=0.1) ax.set_ylabel(r'$\Phi_{x=10}$ (mV)', labelpad=0) ax.text(-0.2, 1.0, 'g', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) ax = fig.add_subplot(5, 3, 8) #set lims ax.set_xlim(0, TEMPLATELEN) ax.set_ylim( templatesFlt[np.isfinite(templatesFlt[:, 0]), :][:, TEMPLATELEN * 1:TEMPLATELEN * 2].min(), templatesFlt[np.isfinite(templatesFlt[:, 0]), :][:, TEMPLATELEN * 1:TEMPLATELEN * 2].max()) #create linecollections line_segments = LineCollection([zip(np.arange(TEMPLATELEN), x) \ for x in templatesFlt[argsort, TEMPLATELEN*1:TEMPLATELEN*2]], linewidths=(1), linestyles='solid', norm=LogNorm(), cmap = plt.cm.get_cmap(cmap, 51), rasterized=True) line_segments.set_array(ISI[argsort]) ax.add_collection(line_segments) for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlabel('samples (-)', labelpad=0.1) ax.set_ylabel(r'$\Phi_{x=50}$ (mV)', labelpad=0) ax.text(-0.2, 1.0, 'h', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) ax = fig.add_subplot(5, 3, 9) #set lims ax.set_xlim(0, TEMPLATELEN) ax.set_ylim( templatesFlt[np.isfinite(templatesFlt[:, 0]), :][:, TEMPLATELEN * 2:TEMPLATELEN * 3].min(), templatesFlt[np.isfinite(templatesFlt[:, 0]), :][:, TEMPLATELEN * 2:TEMPLATELEN * 3].max()) #create linecollections line_segments = LineCollection([zip(np.arange(TEMPLATELEN), x) \ for x in templatesFlt[argsort, TEMPLATELEN*2:TEMPLATELEN*3]], linewidths=(1), linestyles='solid', norm=LogNorm(), cmap = plt.cm.get_cmap(cmap, 51), rasterized=True) line_segments.set_array(ISI[argsort]) ax.add_collection(line_segments) plt.sci(line_segments) # This allows interactive changing of the colormap. for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlabel('samples (-)', labelpad=0.1) ax.set_ylabel(r'$\Phi_{x=100}$ (mV)', labelpad=0) ax.text(-0.2, 1.0, 'i', horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) for i in xrange(3): ax = fig.add_subplot(5, 3, i + 10) sc = ax.scatter(spikewidths_flt[i, argsort], amplitudes_flt[i, argsort], marker='o', edgecolors='none', s=5, c=ISI[argsort], norm=LogNorm(), cmap=plt.cm.get_cmap(cmap, 51), label='filtered', alpha=1, clip_on=False, rasterized=True) if i == 0: ax.set_ylabel('amplitude (mV)', labelpad=0) ax.set_xlabel('width (ms)', labelpad=0.1) ax.set_xlim([spikewidths_flt[i, :].min(), spikewidths_flt[i, :].max()]) ax.set_ylim([amplitudes_flt[i, :].min(), amplitudes_flt[i, :].max()]) for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.text(-0.2, 1.0, alphabet[i + 9], horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) for i in xrange(3): ax = fig.add_subplot(5, 3, i + 13) sc = ax.scatter(ISI, amplitudes_flt[i, :], marker='o', edgecolors='none', s=5, facecolors='k', label='filtered', alpha=1, clip_on=False, rasterized=True) if i == 0: ax.set_ylabel('amplitude (mV)', labelpad=0) ax.set_xlabel('ISI (ms)', labelpad=0.1) ax.set_xlim([ISI.min(), ISI.max()]) ax.set_ylim([amplitudes_flt[i, :].min(), amplitudes_flt[i, :].max()]) ax.semilogx() for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') # don't draw spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.text(-0.2, 1.0, alphabet[i + 12], horizontalalignment='center', verticalalignment='bottom', fontsize=18, fontweight='demibold', transform=ax.transAxes) return fig
import matplotlib.pyplot as plt import matplotlib.pylab as plb import matplotlib.path as pth import matplotlib.compat as cmp x = np.linspace(-np.pi, np.pi, 256) S, C = np.sin(x), np.cos(x) y = np.lexsort(k, a) plt.sin() plt.plot() plt.scatter(x, y, s, m) plt.sci(x) plt.semilogy() plt.sca() plt.sci(im) plt.semilogx(x, y) plt.silent_list(1) plt.sci(2) plt.sca(1) plt.scatter(1, 2) plt.savefig(1, 2) plt.savefig plt.stackplot(1, 3) plt.s #================================================================================= class some_class(object): """ This is the docstring of this class containing information
norm = colors.Normalize(vmin=vmin, vmax=vmax) for i, im in enumerate(images): im.set_norm(norm) if i > 0: images[0].callbacksSM.connect('changed', ImageFollower(im)) #************** # Colorbar #************** ## The colorbar is also based on this master image. #cax = fig.add_axes([0.82, 0.25, 0.025, 0.5]) #fig.colorbar(images[0], cax, orientation='vertical') # We need the following only if we want to run this interactively and # modify the colormap: axes(ax[0]) # Return the current axes to the first one, sci(images[0]) # because the current image must be in current axes. #************** # save fig #************** path_out = '../fig' if not os.path.exists(path_out): os.makedirs(path_out) plt.savefig(path_out + '/' + dat_type + '_s' + str(sn) + '_rec_slice' + str(rec_y) + '.png',figsize=(8,4),dpi=300) show()
def generateVoltChart(tree, rawOut, modelDir, neatoLayout=True): ''' Map the voltages on a feeder over time using a movie.''' # We need to timestamp frames with the system clock to make sure the browser caches them appropriately. genTime = str(datetime.datetime.now()).replace(':', '.') # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob) == dict and ob.get('bustype', '') == 'SWING': feedVoltage = float(ob.get('nominal_voltage', 1)) # Make a graph object. fGraph = feeder.treeToNxGraph(tree) if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) # was formerly : positions = nx.graphviz_layout(cleanG, prog='neato') but this threw an error positions = nx.nx_agraph.graphviz_layout(cleanG, prog='neato') else: rawPositions = {n: fGraph.node[n].get('pos', (0, 0)) for n in fGraph} #HACK: the import code reverses the y coords. def yFlip(pair): try: return (pair[0], -1.0 * pair[1]) except: return (0, 0) positions = {k: yFlip(rawPositions[k]) for k in rawPositions} # Plot all time steps. nodeVolts = {} for step, stamp in enumerate(rawOut['aVoltDump.csv']['# timestamp']): # Build voltage map. nodeVolts[step] = {} for nodeName in [ x for x in rawOut.get('aVoltDump.csv', {}).keys() + rawOut.get('1nVoltDump.csv', {}).keys() + rawOut.get('1mVoltDump.csv', {}).keys() if x != '# timestamp' ]: allVolts = [] for phase in ['a', 'b', 'c', '1n', '2n', '1m', '2m']: try: voltStep = rawOut[phase + 'VoltDump.csv'][nodeName][step] except: continue # the nodeName doesn't have the phase we're looking for. # HACK: Gridlab complex number format sometimes uses i, sometimes j, sometimes d. WTF? if type(voltStep) is str: voltStep = voltStep.replace('i', 'j') v = complex(voltStep) phaseVolt = abs(v) if phaseVolt != 0.0: if _digits(phaseVolt) > 3: # Normalize to 120 V standard phaseVolt = phaseVolt * (120 / feedVoltage) allVolts.append(phaseVolt) # HACK: Take average of all phases to collapse dimensionality. nodeVolts[step][nodeName] = avg(allVolts) # Line current calculations lineCurrents = {} if os.path.exists(pJoin(modelDir, 'OH_line_current_phaseA.csv')): for step, stamp in enumerate( rawOut['OH_line_current_phaseA.csv']['# timestamp']): lineCurrents[step] = {} currentArray = [] # Finding currents of all phases on the line for key in [ x for x in rawOut.get('OH_line_current_phaseA.csv', {}).keys() if x != '# timestamp' ]: currA = rawOut['OH_line_current_phaseA.csv'][key][step] currB = rawOut['OH_line_current_phaseB.csv'][key][step] currC = rawOut['OH_line_current_phaseC.csv'][key][step] flowDir = rawOut['OH_line_flow_direc.csv'][key][step] lineRating = rawOut['OH_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else: direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA), abs(currB), abs(currC)) directedCurrent = float(maxCurrent / lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'], tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent # Underground Lines if os.path.exists(pJoin(modelDir, 'UG_line_current_phaseA.csv')): for step, stamp in enumerate( rawOut['UG_line_current_phaseA.csv']['# timestamp']): currentArray = [] # Finding currents of all phases on the line for key in [ x for x in rawOut.get('UG_line_current_phaseA.csv', {}).keys() if x != '# timestamp' ]: currA = rawOut['UG_line_current_phaseA.csv'][key][step] currB = rawOut['UG_line_current_phaseB.csv'][key][step] currC = rawOut['UG_line_current_phaseC.csv'][key][step] flowDir = rawOut['UG_line_flow_direc.csv'][key][step] lineRating = rawOut['UG_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else: direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA), abs(currB), abs(currC)) directedCurrent = float(maxCurrent / lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'], tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent for step in lineCurrents: for edge in fGraph.edges(): if edge not in lineCurrents[step].keys(): lineCurrents[step][edge] = 0 # Draw animation. voltChart = plt.figure(figsize=(15, 15)) plt.axes(frameon=0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list( 'custColMap', [(0.0, 'blue'), (0.25, 'darkgray'), (0.75, 'darkgray'), (1.0, 'yellow')]) custom_cm.set_under(color='black') current_cm = matplotlib.colors.LinearSegmentedColormap.from_list( 'custColMap', [(0.0, 'green'), (0.999999, 'green'), (1.0, 'red')]) # current_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(-1.0,'green'),(0.0, 'gray'),(1.0,'red'),(1.0,'red')]) # use edge color to set color and dashness of overloaded/negative currents if len(lineCurrents) > 0: edgeIm = nx.draw_networkx_edges( fGraph, pos=positions, edge_color=[lineCurrents[0].get(n, 0) for n in fGraph.edges()], edge_cmap=current_cm) else: edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes( fGraph, pos=positions, node_color=[nodeVolts[0].get(n, 0) for n in fGraph.nodes()], linewidths=0, node_size=30, cmap=custom_cm) plt.sci(nodeIm) plt.clim(110, 130) plt.colorbar() plt.title(rawOut['aVoltDump.csv']['# timestamp'][0]) def update(step): nodeColors = np.array( [nodeVolts[step].get(n, 0) for n in fGraph.nodes()]) if len(lineCurrents) > 0: edgeColors = np.array( [lineCurrents[step].get(n, 0) for n in fGraph.edges()]) edgeIm.set_array(edgeColors) plt.title(rawOut['aVoltDump.csv']['# timestamp'][step]) nodeIm.set_array(nodeColors) return nodeColors, mapTimestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") anim = FuncAnimation(voltChart, update, frames=len(rawOut['aVoltDump.csv']['# timestamp']), interval=200, blit=False) anim.save(pJoin(modelDir, 'voltageChart_' + mapTimestamp + '.mp4'), codec='h264', extra_args=['-pix_fmt', 'yuv420p']) # Reclaim memory by closing, deleting and garbage collecting the last chart. voltChart.clf() plt.close() del voltChart gc.collect() return genTime, mapTimestamp
def plot(data, mesh, shade_pml=False, axis=None, ticks=True, update=None, slice3d=(0,0,0), **kwargs): """ Assumes that data has no ghost padding.""" data.shape = -1,1 sh_bc = mesh.shape(include_bc=True) sh_primary = mesh.shape() if data.shape == sh_bc: has_bc = True plot_shape = mesh.shape(include_bc=True, as_grid=True) elif data.shape == sh_primary: has_bc = False plot_shape = mesh.shape(as_grid=True) else: raise ValueError('Shape mismatch between domain and data.') if axis is None: ax = plt.gca() else: ax = axis data = data.reshape(plot_shape) if mesh.dim == 1: if update is None: zs, = mesh.mesh_coords() ret, = ax.plot(zs,data) if has_bc: ax.axvline(mesh.domain.parameters['z']['lbound'], color='r') ax.axvline(mesh.domain.parameters['z']['rbound'], color='r') else: update.set_ydata(data) ret = update if mesh.dim == 2: data = data.T if update is None: im = ax.imshow(data, interpolation='nearest', aspect='auto', **kwargs) if ticks: mesh_tickers(mesh) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'x', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml) else: update.set_data(data) im = update # Update current image for the colorbar plt.sci(im) ret = im if mesh.dim == 3: if update is None: # X-Y plot ax = plt.subplot(2,2,1) imslice = int(slice3d[2]) # z slice pltdata = data[:,:,imslice:(imslice+1)].squeeze() imxy = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs) if ticks: mesh_tickers(mesh, ('y', 'x')) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'y', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'x', 'TB', shade_pml=shade_pml) # X-Z plot ax = plt.subplot(2,2,2) imslice = int(slice3d[1]) # y slice pltdata = data[:,imslice:(imslice+1),:].squeeze().T imxz = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs) if ticks: mesh_tickers(mesh, ('x', 'z')) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'x', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml) # Y-Z plot ax = plt.subplot(2,2,3) imslice = int(slice3d[0]) # x slice pltdata = data[imslice:(imslice+1),:,:].squeeze().T imyz = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs) if ticks: mesh_tickers(mesh, ('y', 'z')) else: ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) if has_bc: draw_pml(mesh, 'y', 'LR', shade_pml=shade_pml) draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml) update = [imxy, imxz, imyz] plt.sci(imyz) else: imslice = int(slice3d[2]) # z slice pltdata = data[:,:,imslice:(imslice+1)].squeeze() update[0].set_data(pltdata) imslice = int(slice3d[1]) # y slice pltdata = data[:,imslice:(imslice+1),:].squeeze().T update[1].set_data(pltdata) imslice = int(slice3d[0]) # x slice pltdata = data[imslice:(imslice+1),:,:].squeeze().T update[2].set_data(pltdata) ret = update return ret
def plot(self, axes=None, annotate=True, title="SunPy Composite Plot", **matplot_args): """Plots the composite map object by calling :meth:`~sunpy.map.GenericMap.plot` or :meth:`~sunpy.map.GenericMap.draw_contours`. By default, each map is plotted as an image. If a given map has levels defined (via :meth:`~sunpy.map.CompositeMap.set_levels`), that map will instead be plotted as contours. Parameters ---------- axes: `~matplotlib.axes.Axes` or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. annotate : `bool` If true, the data is plotted at it's natural scale; with title and axis labels. title : `str` Title of the composite map. **matplot_args : `dict` Any additional Matplotlib arguments that should be used when plotting. Returns ------- ret : `list` List of axes image or quad contour sets that have been plotted. Notes ----- Images are plotted using either `~matplotlib.axes.Axes.imshow` or `~matplotlib.axes.Axes.pcolormesh`, and contours are plotted using `~matplotlib.axes.Axes.contour`. The Matplotlib arguments accepted by the plotting method are passed to it. (For compatability reasons, we enforce a more restrictive set of accepted `~matplotlib.axes.Axes.pcolormesh` arguments.) If any Matplotlib arguments are not used by any plotting method, a ``TypeError`` will be raised. The ``sunpy.map.compositemap`` module includes variables which list the full set of arguments passed to each plotting method. These are: >>> import sunpy.map.compositemap >>> sorted(sunpy.map.compositemap.ACCEPTED_IMSHOW_KWARGS) {ACCEPTED_IMSHOW_KWARGS} >>> sorted(sunpy.map.compositemap.ACCEPTED_PCOLORMESH_KWARGS) {ACCEPTED_PCOLORMESH_KWARGS} >>> sorted(sunpy.map.compositemap.ACCEPTED_CONTOUR_KWARGS) {ACCEPTED_CONTOUR_KWARGS} If a transformation is required to overlay the maps with the correct alignment, the plot limits may need to be manually set because Matplotlib autoscaling may not work as intended. """ # If axes are not provided, create a WCSAxes based on the first map if not axes: axes = wcsaxes_compat.gca_wcs(self._maps[0].wcs) if annotate: axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0], self._maps[0].spatial_units[0])) axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1], self._maps[0].spatial_units[1])) axes.set_title(title) # Checklist to determine unused keywords in `matplot_args` unused_kwargs = set(matplot_args.keys()) # Define a list of plotted objects ret = [] # Plot layers of composite map for m in self._maps: # Parameters for plotting params = { "alpha": m.alpha, "zorder": m.zorder, } params.update(matplot_args) # The request to show a map layer rendered as a contour is indicated by a # non False levels property. if m.levels is False: # We tell GenericMap.plot() that we need to autoalign the map if wcsaxes_compat.is_wcsaxes(axes): params['autoalign'] = True # Filter `matplot_args` if params.get('autoalign', None) in (True, 'pcolormesh'): accepted_kwargs = ACCEPTED_PCOLORMESH_KWARGS else: accepted_kwargs = ACCEPTED_IMSHOW_KWARGS for item in matplot_args.keys(): if item not in accepted_kwargs: del params[item] else: # mark as used unused_kwargs -= {item} params['annotate'] = False ret.append(m.plot(**params)) else: # Filter `matplot_args` for item in matplot_args.keys(): if item not in ACCEPTED_CONTOUR_KWARGS: del params[item] else: # mark as used unused_kwargs -= {item} ret.append(m.draw_contours(m.levels, **params)) # Set the label of the first line so a legend can be created ret[-1].collections[0].set_label(m.name) if len(unused_kwargs) > 0: raise TypeError(f'plot() got unexpected keyword arguments {unused_kwargs}') # Adjust axes extents to include all data axes.axis('image') # Set current image (makes colorbar work) plt.sci(ret[0]) return ret
# Set the first image as the master, with all the others # observing it for changes in cmap or norm. class ImageFollower: 'update image in response to changes in clim or cmap on another image' def __init__(self, follower): self.follower = follower def __call__(self, leader): self.follower.set_cmap(leader.get_cmap()) self.follower.set_clim(leader.get_clim()) norm = colors.Normalize(vmin=vmin, vmax=vmax) for i, im in enumerate(images): im.set_norm(norm) if i > 0: images[0].callbacksSM.connect('changed', ImageFollower(im)) # The colorbar is also based on this master image. fig.colorbar(images[0], cax, orientation='horizontal') # We need the following only if we want to run this sci(images[0]) show()
def date_heatmap(series, start=None, end=None, mean=False, ax=None, **kwargs): '''Plot a calendar heatmap given a datetime series. Arguments: series (pd.Series): A series of numeric values with a datetime index. Values occurring on the same day are combined by sum. start (Any): The first day to be considered in the plot. The value can be anything accepted by :func:`pandas.to_datetime`. The default is the earliest date in the data. end (Any): The last day to be considered in the plot. The value can be anything accepted by :func:`pandas.to_datetime`. The default is the latest date in the data. mean (bool): Combine values occurring on the same day by mean instead of sum. ax (matplotlib.Axes or None): The axes on which to draw the heatmap. The default is the current axes in the :module:`~matplotlib.pyplot` API. **kwargs: Forwarded to :meth:`~matplotlib.Axes.pcolormesh` for drawing the heatmap. Returns: matplotlib.collections.Axes: The axes on which the heatmap was drawn. This is set as the current axes in the `~matplotlib.pyplot` API. ''' # Combine values occurring on the same day. dates = series.index.floor('D') group = series.groupby(dates) series = group.mean() if mean else group.sum() # Parse start/end, defaulting to the min/max of the index. start = pd.to_datetime(start or series.index.min()) end = pd.to_datetime(end or series.index.max()) # We use [start, end) as a half-open interval below. end += np.timedelta64(1, 'D') # Get the previous/following Sunday to start/end. # Pandas and numpy day-of-week conventions are Monday=0 and Sunday=6. start_sun = start - np.timedelta64((start.dayofweek + 1) % 7, 'D') end_sun = end + np.timedelta64(7 - end.dayofweek - 1, 'D') # Create the heatmap and track ticks. num_weeks = (end_sun - start_sun).days // 7 heatmap = np.zeros((7, num_weeks)) ticks = {} # week number -> month name for week in range(num_weeks): for day in range(7): date = start_sun + np.timedelta64(7 * week + day, 'D') if date.day == 1: ticks[week] = MONTHS[date.month - 1] if date.dayofyear == 1: ticks[week] += f'\n{date.year}' if start <= date < end: heatmap[day, week] = series.get(date, 0) # Get the coordinates, offset by 0.5 to align the ticks. y = np.arange(8) - 0.5 x = np.arange(num_weeks + 1) - 0.5 # Plot the heatmap. Prefer pcolormesh over imshow so that the figure can be # vectorized when saved to a compatible format. We must invert the axis for # pcolormesh, but not for imshow, so that it reads top-bottom, left-right. ax = ax or plt.gca() mesh = ax.pcolormesh(x, y, heatmap, **kwargs) ax.invert_yaxis() # Set the ticks. ax.set_xticks(list(ticks.keys())) ax.set_xticklabels(list(ticks.values())) ax.set_yticks(np.arange(7)) ax.set_yticklabels(DAYS) # Set the current image and axes in the pyplot API. plt.sca(ax) plt.sci(mesh) return ax
images = [] vmin = 1e40 vmax = -1e40 for i in range(Nr): for j in range(Nc): pos = [0.075 + j*1.1*w, 0.18 + i*1.2*h, w, h] a = fig.add_axes(pos) if i > 0: a.set_xticklabels([]) data =((1+i+j)/10.0)*rand(10,20)*1e-6 dd = ravel(data) vmin = min(vmin, amin(dd)) vmax = max(vmax, amax(dd)) images.append(a.imshow(data, cmap=cmap)) ax.append(a) class ImageFollower: 'update image in response to changes in clim or cmap on another image' def __init__(self, follower): self.follower = follower def __call__(self, leader): self.follower.set_cmap(leader.get_cmap()) self.follower.set_clim(leader.get_clim()) norm = colors.Normalize(vmin=vmin, vmax=vmax) for i, im in enumerate(images): im.set_norm(norm) if i > 0: images[0].callbacksSM.connect('changed', ImageFollower(im)) fig.colorbar(images[0], cax, orientation='horizontal') sci(images[0]) show()
def ellipses(x, y, w, h=None, rot=0.0, c='b', vmin=None, vmax=None, **kwargs): """ Make a scatter plot of ellipses. Parameters ---------- x, y : scalar or array_like, shape (n, ) Center of ellipses. w, h : scalar or array_like, shape (n, ) Total length (diameter) of horizontal/vertical axis. `h` is set to be equal to `w` by default, ie. circle. rot : scalar or array_like, shape (n, ) Rotation in degrees (anti-clockwise). c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- paths : `~matplotlib.collections.PathCollection` Examples -------- a = np.arange(11) ellipses(a, a, w=4, h=a, rot=a*30, c=a, alpha=0.5, ec='none') plt.colorbar() License -------- This code is under [The BSD 3-Clause License] (http://opensource.org/licenses/BSD-3-Clause) """ if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) # You can set `facecolor` with an array for each patch, # while you can only set `facecolors` with a value for all. if h is None: h = w zipped = np.broadcast(x, y, w, h, rot) patches = [ Ellipse((x_, y_), w_, h_, rot_) for x_, y_, w_, h_, rot_ in zipped ] collection = PatchCollection(patches, **kwargs) if c is not None: c = np.broadcast_to(c, zipped.shape).ravel() collection.set_array(c) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() plt.draw_if_interactive() if c is not None: plt.sci(collection) return collection
def specshow(data, x_coords=None, y_coords=None, x_axis=None, y_axis=None, sr=22050, hop_length=512, fmin=None, fmax=None, bins_per_octave=12, **kwargs): '''Display a spectrogram/chromagram/cqt/etc. Parameters ---------- data : np.ndarray [shape=(d, n)] Matrix to display (e.g., spectrogram) sr : number > 0 [scalar] Sample rate used to determine time scale in x-axis. hop_length : int > 0 [scalar] Hop length, also used to determine time scale in x-axis x_axis : None or str y_axis : None or str Range for the x- and y-axes. Valid types are: - None, 'none', or 'off' : no axis decoration is displayed. Frequency types: - 'linear', 'fft', 'hz' : frequency range is determined by the FFT window and sampling rate. - 'log' : the spectrum is displayed on a log scale. - 'mel' : frequencies are determined by the mel scale. - 'cqt_hz' : frequencies are determined by the CQT scale. - 'cqt_note' : pitches are determined by the CQT scale. All frequency types are plotted in units of Hz. Categorical types: - 'chroma' : pitches are determined by the chroma filters. Pitch classes are arranged at integer locations (0-11). - 'tonnetz' : axes are labeled by Tonnetz dimensions (0-5) - 'frames' : markers are shown as frame counts. Time types: - 'time' : markers are shown as milliseconds, seconds, minutes, or hours - 'lag' : like time, but past the half-way point counts as negative values. All time types are plotted in units of seconds. Other: - 'tempo' : markers are shown as beats-per-minute (BPM) using a logarithmic scale. x_coords : np.ndarray [shape=data.shape[1]+1] y_coords : np.ndarray [shape=data.shape[0]+1] Optional positioning coordinates of the input data. These can be use to explicitly set the location of each element `data[i, j]`, e.g., for displaying beat-synchronous features in natural time coordinates. If not provided, they are inferred from `x_axis` and `y_axis`. fmin : float > 0 [scalar] or None Frequency of the lowest spectrogram bin. Used for Mel and CQT scales. If `y_axis` is `cqt_hz` or `cqt_note` and `fmin` is not given, it is set by default to `note_to_hz('C1')`. fmax : float > 0 [scalar] or None Used for setting the Mel frequency scales bins_per_octave : int > 0 [scalar] Number of bins per octave. Used for CQT frequency scale. kwargs : additional keyword arguments Arguments passed through to `matplotlib.pyplot.pcolormesh`. Returns ------- axes The axis handle for the figure. See Also -------- cmap : Automatic colormap detection matplotlib.pyplot.pcolormesh Examples -------- Visualize an STFT power spectrum >>> import matplotlib.pyplot as plt >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> plt.figure(figsize=(12, 8)) >>> D = librosa.logamplitude(np.abs(librosa.stft(y))**2, ref_power=np.max) >>> plt.subplot(4, 2, 1) >>> librosa.display.specshow(D, y_axis='linear') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Linear-frequency power spectrogram') Or on a logarithmic scale >>> plt.subplot(4, 2, 2) >>> librosa.display.specshow(D, y_axis='log') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Log-frequency power spectrogram') Or use a CQT scale >>> CQT = librosa.logamplitude(librosa.cqt(y, sr=sr)**2, ref_power=np.max) >>> plt.subplot(4, 2, 3) >>> librosa.display.specshow(CQT, y_axis='cqt_note') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Constant-Q power spectrogram (note)') >>> plt.subplot(4, 2, 4) >>> librosa.display.specshow(CQT, y_axis='cqt_hz') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Constant-Q power spectrogram (Hz)') Draw a chromagram with pitch classes >>> C = librosa.feature.chroma_cqt(y=y, sr=sr) >>> plt.subplot(4, 2, 5) >>> librosa.display.specshow(C, y_axis='chroma') >>> plt.colorbar() >>> plt.title('Chromagram') Force a grayscale colormap (white -> black) >>> plt.subplot(4, 2, 6) >>> librosa.display.specshow(D, cmap='gray_r', y_axis='linear') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Linear power spectrogram (grayscale)') Draw time markers automatically >>> plt.subplot(4, 2, 7) >>> librosa.display.specshow(D, x_axis='time', y_axis='log') >>> plt.colorbar(format='%+2.0f dB') >>> plt.title('Log power spectrogram') Draw a tempogram with BPM markers >>> plt.subplot(4, 2, 8) >>> Tgram = librosa.feature.tempogram(y=y, sr=sr) >>> librosa.display.specshow(Tgram, x_axis='time', y_axis='tempo') >>> plt.colorbar() >>> plt.title('Tempogram') >>> plt.tight_layout() Draw beat-synchronous chroma in natural time >>> plt.figure() >>> tempo, beat_f = librosa.beat.beat_track(y=y, sr=sr, trim=False) >>> beat_f = librosa.util.fix_frames(beat_f, x_max=C.shape[1]) >>> Csync = librosa.util.sync(C, beat_f, aggregate=np.median) >>> beat_t = librosa.frames_to_time(beat_f, sr=sr) >>> ax1 = plt.subplot(2,1,1) >>> librosa.display.specshow(C, y_axis='chroma', x_axis='time') >>> plt.title('Chroma (linear time)') >>> ax2 = plt.subplot(2,1,2, sharex=ax1) >>> librosa.display.specshow(Csync, y_axis='chroma', x_axis='time', ... x_coords=beat_t) >>> plt.title('Chroma (beat time)') >>> plt.tight_layout() ''' kwargs.setdefault('shading', 'flat') if np.issubdtype(data.dtype, np.complex): warnings.warn('Trying to display complex-valued input. ' 'Showing magnitude instead.') data = np.abs(data) kwargs.setdefault('cmap', cmap(data)) all_params = dict(kwargs=kwargs, sr=sr, fmin=fmin, fmax=fmax, bins_per_octave=bins_per_octave, hop_length=hop_length) # Get the x and y coordinates y_coords = __mesh_coords(y_axis, y_coords, data.shape[0], **all_params) x_coords = __mesh_coords(x_axis, x_coords, data.shape[1], **all_params) axes = plt.gca() out = axes.pcolormesh(x_coords, y_coords, data, **kwargs) plt.sci(out) axes.set_xlim(x_coords.min(), x_coords.max()) axes.set_ylim(y_coords.min(), y_coords.max()) # Set up axis scaling __scale_axes(axes, x_axis, 'x') __scale_axes(axes, y_axis, 'y') # Construct tickers and locators __decorate_axis(axes.xaxis, x_axis) __decorate_axis(axes.yaxis, y_axis) return axes
def showMatrix(matrix, x_array=None, y_array=None, **kwargs): """Show a matrix using :meth:`~matplotlib.axes.Axes.imshow`. Curves on x- and y-axis can be added. :arg matrix: Matrix to be displayed. :type matrix: :class:`~numpy.ndarray` :arg x_array: Data to be plotted above the matrix. :type x_array: :class:`~numpy.ndarray` :arg y_array: Data to be plotted on the left side of the matrix. :type y_array: :class:`~numpy.ndarray` :arg percentile: A percentile threshold to remove outliers, i.e. only showing data within *p*-th to *100-p*-th percentile. :type percentile: float""" import matplotlib.pyplot as plt from matplotlib import cm, ticker from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec from matplotlib.collections import LineCollection from matplotlib.pyplot import imshow, gca, sca, sci p = kwargs.pop('percentile', None) if p is not None: vmin = np.percentile(matrix, p) vmax = np.percentile(matrix, 100-p) else: vmin = vmax = None W = H = 8 ticklabels = kwargs.pop('ticklabels', None) allticks = kwargs.pop('allticks', False) # this argument is temporary and will be replaced by better implementation origin = kwargs.pop('origin', 'lower') if x_array is not None and y_array is not None: nrow = 2; ncol = 2 i = 1; j = 1 width_ratios = [1, W] height_ratios = [1, H] aspect = 'auto' elif x_array is not None and y_array is None: nrow = 2; ncol = 1 i = 1; j = 0 width_ratios = [W] height_ratios = [1, H] aspect = 'auto' elif isinstance(y_array, Phylo.BaseTree.Tree): nrow = 2; ncol = 2 i = 1; j = 1 width_ratios = [W, W] height_ratios = [H, H] aspect = 'auto' elif x_array is None and y_array is not None: nrow = 1; ncol = 2 i = 0; j = 1 width_ratios = [1, W] height_ratios = [H] aspect = 'auto' else: nrow = 1; ncol = 1 i = 0; j = 0 width_ratios = [W] height_ratios = [H] aspect = None main_index = (i,j) upper_index = (i-1,j) left_index = (i,j-1) complex_layout = nrow > 1 or ncol > 1 cb = kwargs.pop('colorbar', True) if complex_layout: if cb: outer = GridSpec(1, 2, width_ratios = [15, 1], hspace=0.) gs = GridSpecFromSubplotSpec(nrow, ncol, subplot_spec = outer[0], width_ratios=width_ratios, height_ratios=height_ratios, hspace=0., wspace=0.) gs_bar = GridSpecFromSubplotSpec(nrow, 1, subplot_spec = outer[1], height_ratios=height_ratios, hspace=0., wspace=0.) else: gs = GridSpec(nrow, ncol, width_ratios=width_ratios, height_ratios=height_ratios, hspace=0., wspace=0.) lines = [] if nrow > 1: ax1 = plt.subplot(gs[upper_index]) if isinstance(y_array, Phylo.BaseTree.Tree): pass else: ax1.set_xticklabels([]) y = x_array x = np.arange(len(y)) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) cmap = cm.jet(y) lcy = LineCollection(segments, array=x, linewidths=1, cmap='jet') lines.append(lcy) ax1.add_collection(lcy) ax1.set_xlim(x.min(), x.max()) ax1.set_ylim(y.min(), y.max()) ax1.axis('off') if ncol > 1: ax2 = plt.subplot(gs[left_index]) if isinstance(y_array, Phylo.BaseTree.Tree): Phylo.draw(y_array, do_show=False, axes=ax2, **kwargs) else: ax2.set_xticklabels([]) y = y_array x = np.arange(len(y)) points = np.array([y, x]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) cmap = cm.jet(y) lcx = LineCollection(segments, array=y, linewidths=1, cmap='jet') lines.append(lcx) ax2.add_collection(lcx) ax2.set_xlim(y.min(), y.max()) ax2.set_ylim(x.min(), x.max()) ax2.invert_xaxis() ax2.axis('off') if complex_layout: ax3 = plt.subplot(gs[main_index]) else: ax3 = gca() kwargs['origin'] = origin if not 'cmap' in kwargs: kwargs['cmap'] = 'jet' im = ax3.imshow(matrix, aspect=aspect, vmin=vmin, vmax=vmax, **kwargs) #ax3.set_xlim([-0.5, matrix.shape[0]+0.5]) #ax3.set_ylim([-0.5, matrix.shape[1]+0.5]) if ticklabels is not None: ax3.xaxis.set_major_formatter(ticker.IndexFormatter(ticklabels)) if ncol == 1: ax3.yaxis.set_major_formatter(ticker.IndexFormatter(ticklabels)) if allticks: ax3.xaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.)) ax3.yaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.)) else: ax3.xaxis.set_major_locator(ticker.AutoLocator()) ax3.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax3.yaxis.set_major_locator(ticker.AutoLocator()) ax3.yaxis.set_minor_locator(ticker.AutoMinorLocator()) if ncol > 1: ax3.yaxis.set_major_formatter(ticker.NullFormatter()) colorbar = None if cb: if complex_layout: ax4 = plt.subplot(gs_bar[-1]) colorbar = plt.colorbar(mappable=im, cax=ax4) else: colorbar = plt.colorbar(mappable=im) sca(ax3) sci(im) return im, lines, colorbar