def plotReachSet_norm1(self, NUM, figname): fig = p.figure() for j in range(n): ax = fig.add_subplot(2,2,j+1 , aspect='equal') ax.set_xlim(0, 4) ax.set_ylim(0, 1) ax.set_xlabel('$x_'+str(j+1)+'$') ax.set_ylabel('$y_'+str(j+1)+'$') for trace in self: for i in [int(floor(k*len(trace.T)/NUM)) for k in range(NUM)]: verts = [(trace.x[i][j] + 1/trace.d_norm1[i][2*j], trace.y[i][j] ), (trace.x[i][j] , trace.y[i][j] - 1/trace.d_norm1[i][2*j+1]), (trace.x[i][j] - 1/trace.d_norm1[i][2*j], trace.y[i][j] ), (trace.x[i][j] , trace.y[i][j] + 1/trace.d_norm1[i][2*j+1])] # poly = Ellipse((trace.x[i][j],trace.y[i][j]), width=trace.d1[i], height=trace.d2[i], angle=trace.theta[i]) poly = Polygon(verts, facecolor='0.8', edgecolor='k') ax.add_artist(poly) poly.set_clip_box(ax.bbox) poly.set_alpha(1) if i==0: poly.set_facecolor('r') else: poly.set_facecolor(p.rand(3)) #for trace in self: #e = Ellipse((trace.x[0][j],trace.y[0][j]), width=trace.d1[0], height=trace.d2[0], angle=trace.theta[0]) #ax.add_artist(e) #e.set_clip_box(ax.bbox) #e.set_alpha(1) #e.set_facecolor('r') #e.set_edgecolor('r') p.savefig(figname)
def parallelogram_gen(origin, side1, side2, size, opacity = 1): # We rescale the points for the [1,1]^2 domain first_point = origin/size side1_scaled = side1/size side2_scaled = side2/size # Getting the points second_point= (first_point + side1_scaled) fourth_point= (first_point + side2_scaled) third_point = side1_scaled+side2_scaled+first_point x = [first_point[0],second_point[0],third_point[0],fourth_point[0]] y = [first_point[1],second_point[1],third_point[1],fourth_point[1]]; fig = plt.figure(0,frameon=False,figsize=(1,1), dpi=size) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() # Paralllogelogram p = Polygon(xy=list(zip(x,y))) ax.add_patch(p) p.set_alpha(None) p.set_facecolor(np.zeros(3)) ax.set_xlim(0, 1) ax.set_ylim(0, 1) fig.add_axes(ax) plt.axis('off') # Convert figure to data data = fig2data(fig) plt.close(fig) # Take just the first color entry data = data[:,:,1] # Normalize the data data = data/data.max() data = np.flip(data,0) return ((data-1)*opacity)+1
def overlapping_bricks(self, candidates, map_petals=False): """Convert a list of potentially overlapping bricks into actual overlaps. Parameters ---------- candidates : :class:`list` A list of candidate bricks. map_petals : bool, optional If ``True`` a map of petal number to a list of overlapping bricks is returned. Returns ------- :class:`list` A list of Polygon objects. """ petals = self.petals() petal2brick = dict() bricks = list() for b in candidates: b_ra1, b_ra2 = self.brick_offset(b) brick_corners = np.array([[b_ra1, b.dec1], [b_ra2, b.dec1], [b_ra2, b.dec2], [b_ra1, b.dec2]]) brick = Polygon(brick_corners, closed=True, facecolor='r') for i, p in enumerate(petals): if brick.get_path().intersects_path(p.get_path()): brick.set_facecolor('g') if i in petal2brick: petal2brick[i].append(b.id) else: petal2brick[i] = [b.id] bricks.append(brick) if map_petals: return petal2brick return bricks
def __init__(self, xy, closed=True, plotview=None, **opts): shape = Polygon(xy, closed, **opts) if 'linewidth' not in opts: shape.set_linewidth(1.0) if 'facecolor' not in opts: shape.set_facecolor('r') super(NXpolygon, self).__init__(shape, resize=False, plotview=plotview) self.shape.set_label('Polygon') self.polygon = self.shape
def __init__(self, xy, closed=True, plotview=None, **opts): shape = Polygon(xy, closed, **opts) if 'linewidth' not in opts: shape.set_linewidth(1.0) if 'facecolor' not in opts: shape.set_facecolor('r') super(NXpolygon, self).__init__(shape, resize=False, plotview=plotview) self.shape.set_label('Polygon') self.polygon = self.shape
def draw_enter_exit(self): """plot enter and exit cells on the graph""" start_polygon = Polygon(self.get_polygon_points(self.maze.start), True) exit_polygon = Polygon(self.get_polygon_points(self.maze.exit), True) start_polygon.set_facecolor(self.start_color) exit_polygon.set_facecolor(self.exit_color) exit_polygon.set_alpha(0.4) self.ax.add_patch(start_polygon) self.ax.add_patch(exit_polygon) return
def get_state_maps(list): counter = 0 for x in list: ax = plt.gca() seg = map.states[state_names.index(x)] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) savefig('images/map/map' + str(counter) + '.png', bbox_inches='tight') poly.set_facecolor('None') poly.set_edgecolor('None') counter += 1
class WidthPolygon(object): def __init__(self, ax, x, y, *args, **kwargs): self.ax, self.x, self.y = ax, x, y self.data = list(zip(x, y)) # [(x[0],y[0])] + zip(x,y) + [(x[-1],y[-1])] self.polygon = Polygon(self.data, *args, **kwargs) self.ax.add_patch(self.polygon) self.continuum, = self.ax.plot([x[0], x[-1]], [y[0], y[-1]], color='black', lw=1) def set_data(self, x, y): self.data = list(zip(x, y)) self.polygon.set_xy(self.data) self.continuum.set_data([[x[0], x[-1]], [y[0], y[-1]]]) def set_color(self, color): self.polygon.set_facecolor(color) def set_visible(self, visible): self.polygon.set_visible(visible) self.continuum.set_visible(visible) def __setattr__(self, name, value): if name == 'zoom_ignore': self.polygon.zoom_ignore = value self.continuum.zoom_ignore = value else: object.__setattr__(self, name, value) def delete(self): self.ax.patches.remove(self.polygon) self.ax.lines.remove(self.continuum)
def overlapping_bricks(self, session, map_petals=False): """Perform a geometric calculation to find bricks that overlap a tile. Parameters ---------- session : :class:`sqlalchemy.orm.session.Session` Database connection. map_petals : bool, optional If ``True`` a map of petal number to a list of overlapping bricks is returned. Returns ------- :class:`list` If `map_petals` is ``False``, a list of :class:`~matplotlib.patches.Polygon` objects. Otherwise, a :class:`dict` mapping petal number to the :class:`~lvmspec.database.metadata.Brick` objects that overlap that petal. """ if self._brick_polygons is None and self._petal2brick is None: candidates = self._coarse_overlapping_bricks(session) petals = self.petals() self._petal2brick = dict() self._brick_polygons = list() for b in candidates: b_ra1, b_ra2 = self.brick_offset(b) brick_corners = np.array([[b_ra1, b.dec1], [b_ra2, b.dec1], [b_ra2, b.dec2], [b_ra1, b.dec2]]) brick_poly = Polygon(brick_corners, closed=True, facecolor='r') for i, p in enumerate(petals): if brick_poly.get_path().intersects_path(p.get_path()): brick_poly.set_facecolor('g') if i in self._petal2brick: self._petal2brick[i].append(b) else: self._petal2brick[i] = [b] self._brick_polygons.append(brick_poly) if map_petals: return self._petal2brick return self._brick_polygons
class Roi(object): def __init__(self, xy, name, colour, linewidth=None): ''' A ROI is defined by its vertices (xy coords), a name, and a colour. Input: xy Coordinates of the ROI as a numpy array of shape (2, N). name Name of the ROI, string. colour Colour definition in any format acceptable to matplotlib, ie named (e.g. 'white') or RGBA format (e,g. (1.0, 1.0, 1.0, 1.0)). ''' super(Roi, self).__init__() self.polygon = Polygon(xy, lw=linewidth) self.polygon.set_facecolor('none') self.name = name self.set_colour(colour) def set_colour(self, colour): self.polygon.set_edgecolor(colour) def get_colour(self): return self.polygon.get_edgecolor() def set_name(self, name): self.name = name def get_name(self): return self.name def set_xy(self): return self.polygon.set_xy() def get_xy(self): return self.polygon.get_xy() def get_polygon(self): return self.polygon
def overlapping_bricks(self, candidates, map_petals=False): """Convert a list of potentially overlapping bricks into actual overlaps. Parameters ---------- candidates : :class:`list` A list of candidate bricks. map_petals : bool, optional If ``True`` a map of petal number to a list of overlapping bricks is returned. Returns ------- :class:`list` A list of Polygon objects. """ petals = self.petals() petal2brick = dict() bricks = list() for b in candidates: b_ra1, b_ra2 = self.brick_offset(b) brick_corners = np.array([[b_ra1, b.dec1], [b_ra2, b.dec1], [b_ra2, b.dec2], [b_ra1, b.dec2]]) brick = Polygon(brick_corners, closed=True, facecolor='r') for i, p in enumerate(petals): if brick.get_path().intersects_path(p.get_path()): brick.set_facecolor('g') if i in petal2brick: petal2brick[i].append(b.id) else: petal2brick[i] = [b.id] bricks.append(brick) if map_petals: return petal2brick return bricks
def animate_polygons(self, frame): point = self.path[frame] polygon = Polygon(self.get_polygon_points(point), True) if point not in [self.maze.start, self.maze.exit]: if point in self.path[:frame]: #backtracking polygon.set_facecolor(self.polygon_backtracking_color) polygon.set_edgecolor(self.polygon_backtracking_edge_color) self.ax.add_patch(polygon) else: polygon.set_facecolor(self.polygon_face_color) polygon.set_edgecolor(self.polygon_edge_color) self.ax.add_patch(polygon) if point == self.maze.exit: polygon.set_facecolor(self.exit_color) polygon.set_alpha(1) self.ax.add_patch(polygon) return []
def plot_fits_map(data, header, stretch='auto', exponent=2, scaleFrac=0.9, cmapName='gist_heat', zMin=None, zMax=None, annEllipseLst=[], annPolyLst=[], bunit=None, lw=1.0, interpolation='Nearest', fig=None, dpi=100, doColbar=True): """ Plot a colourscale image of a FITS map. annEllipseLst is a list of lists: annEllipseLst[0][i] = x_deg annEllipseLst[1][i] = y_deg annEllipseLst[2][i] = minor_deg annEllipseLst[3][i] = major_deg annEllipseLst[4][i] = pa_deg annEllipseLst[5][i] = colour ... optional, default to 'g' annPolyLst is also a list of lists: annPolyLst[0][i] = list of polygon coords = [[x1,y1], [x2, y2] ...] annPolyLst[1][i] = colour of polygon e.g., 'w' """ # Strip unused dimensions from the array data, header = strip_fits_dims(data, header, 2, 5) # Parse the WCS information w = mkWCSDict(header) wcs = pw.WCS(w['header2D']) # Calculate the image vmin and vmax by measuring the range in the inner # 'scale_frac' of the image s = data.shape boxMaxX = int(s[-1] / 2.0 + s[-1] * scaleFrac / 2.0 + 1.0) boxMinX = int(s[-1] / 2.0 - s[-1] * scaleFrac / 2.0 + 1.0) boxMaxY = int(s[-2] / 2.0 + s[-2] * scaleFrac / 2.0 + 1.0) boxMinY = int(s[-2] / 2.0 - s[-2] * scaleFrac / 2.0 + 1.0) dataSample = data[boxMinY:boxMaxY, boxMinX:boxMaxX] measures = calc_stats(dataSample) sigma = abs(measures['max'] / measures['madfm']) if stretch == 'auto': if sigma <= 20: vMin = measures['madfm'] * (-1.5) vMax = measures['madfm'] * 10.0 stretch = 'linear' elif sigma > 20: vMin = measures['madfm'] * (-3.0) vMax = measures['madfm'] * 40.0 stretch = 'linear' elif sigma > 500: vMin = measures['madfm'] * (-7.0) vMax = measures['madfm'] * 200.0 stretch = 'sqrt' if not zMax is None: vMax = max(zMax, measures['max']) if not zMax is None: vMin = zMin # Set the colourscale using an normalizer object normalizer = APLpyNormalize(stretch=stretch, exponent=exponent, vmin=vMin, vmax=vMax) # Setup the figure if fig is None: fig = plt.figure(facecolor='w', figsize=(9.5, 8)) ax = fig.add_axes([0.1, 0.08, 0.9, 0.87]) if w['coord_type'] == 'EQU': ax.set_xlabel('Right Ascension') ax.set_ylabel('Declination') elif w['coord_type'] == 'GAL': ax.set_xlabel('Galactic Longitude (deg)') ax.set_ylabel('Galactic Latitude (deg)') else: ax.set_xlabel('Unknown') ax.set_ylabel('Unknown') cosY = m.cos(m.radians(w['ycent'])) aspect = abs(w['ydelt'] / (w['xdelt'] * cosY)) # Set the format of the major tick mark and labels if w['coord_type'] == 'EQU': f = 15.0 majorFormatterX = FuncFormatter(label_format_hms) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_dms) minorFormattery = None else: f = 1.0 majorFormatterX = FuncFormatter(label_format_deg) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_deg) minorFormattery = None ax.xaxis.set_major_formatter(majorFormatterX) ax.yaxis.set_major_formatter(majorFormatterY) # Set the location of the the major tick marks #xrangeArcmin = abs(w['xmax']-w['xmin'])*(60.0*f) #xmultiple = m.ceil(xrangeArcmin/3.0)/(60.0*f) #yrangeArcmin = abs(w['ymax']-w['ymin'])*60.0 #ymultiple = m.ceil(yrangeArcmin/3.0)/60.0 #majorLocatorX = MultipleLocator(xmultiple) #ax.xaxis.set_major_locator(majorLocatorX) #majorLocatorY = MultipleLocator(ymultiple) #ax.yaxis.set_major_locator(majorLocatorY) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(5)) # Print the image to the axis im = ax.imshow(data, interpolation=interpolation, origin='lower', aspect=aspect, extent=[w['xmax'], w['xmin'], w['ymin'], w['ymax']], cmap=plt.get_cmap(cmapName), norm=normalizer) # Add the colorbar if doColbar: cbar = fig.colorbar(im, pad=0.0) if 'BUNIT' in header: cbar.set_label(header['BUNIT']) else: cbar.set_label('Unknown') if not bunit is None: cbar.set_label(bunit) # Format the colourbar labels - TODO # Set white ticks ax.tick_params(pad=5) for line in ax.xaxis.get_ticklines() + ax.get_yticklines(): line.set_markeredgewidth(1) line.set_color('w') # Create the ellipse source annotations if len(annEllipseLst) > 0: if len(annEllipseLst) >= 5: srcXLst = np.array(annEllipseLst[0]) srcYLst = np.array(annEllipseLst[1]) srcMinLst = np.array(annEllipseLst[2]) srcMajLst = np.array(annEllipseLst[3]) srcPALst = np.array(annEllipseLst[4]) if len(annEllipseLst) >= 6: if type(annEllipseLst[5]) is str: srcEColLst = [annEllipseLst[5]] * len(srcXLst) elif type(annEllipseLst[5]) is list: srcEColLst = annEllipseLst[5] else: rcEColLst = ['g'] * len(srcXLst) else: srcEColLst = ['g'] * len(srcXLst) for i in range(len(srcXLst)): try: el = Ellipse((srcXLst[i], srcYLst[i]), srcMinLst[i], srcMajLst[i], angle=180.0 - srcPALst[i], edgecolor=srcEColLst[i], linewidth=lw, facecolor='none') ax.add_artist(el) except Exception: pass # Create the polygon source annotations if len(annPolyLst) > 0: annPolyCoordLst = annPolyLst[0] if len(annPolyLst) > 1: if type(annPolyLst[1]) is str: annPolyColorLst = [annPolyLst[1]] * len(annPolyCoordLst) elif type(annPolyLst[1]) is list: annPolyColorLst = annPolyLst[1] else: annPolyColorLst = ['g'] * len(annPolyCoordLst) else: annPolyColorLst = ['g'] * len(annPolyCoordLst) for i in range(len(annPolyCoordLst)): cpoly = Polygon(annPolyCoordLst[i], animated=False, linewidth=lw) cpoly.set_edgecolor(annPolyColorLst[i]) cpoly.set_facecolor('none') ax.add_patch(cpoly) return fig
titleax = plt.subplot(gs[0, :5]) ax.axis("off") titleax.axis("off") m = Basemap(projection='eck4', lon_0=160, resolution='c', ax=ax) m.drawcoastlines(linewidth=0, color="#FFFFFF") m.drawmapboundary(color="aqua") m.fillcontinents(color='#cccccc', lake_color='#FFFFFF') # Read shapefile m.readshapefile("data/ne_10m_admin_0_countries/ne_10m_admin_0_countries", "units", drawbounds=False) patches = [] for info, shape in zip(m.units_info, m.units): poly = Polygon(np.array(shape), True) poly.set_facecolor('none') poly.set_linewidth(0) poly.set_edgecolor("#000000") poly.set_zorder(1) poly = ax.add_patch(poly) patches.append(poly) x1, y1 = m(coords["lng"].values, coords["lat"].values) _c = [scalarMap.to_rgba(groups.index(i)) for i in groups] p = m.scatter(x1, y1, marker="o", alpha=1, color=_c, zorder=2, sizes=[0] * coords.shape[0])
def plot_fits_map(data, header, stretch='auto', exponent=2, scaleFrac=0.9, cmapName='gist_heat', zMin=None, zMax=None, annEllipseLst=[], annPolyLst=[], bunit=None, lw=1.0, interpolation='Nearest', fig=None, dpi=100, doColbar=True): """ Plot a colourscale image of a FITS map. annEllipseLst is a list of lists: annEllipseLst[0][i] = x_deg annEllipseLst[1][i] = y_deg annEllipseLst[2][i] = minor_deg annEllipseLst[3][i] = major_deg annEllipseLst[4][i] = pa_deg annEllipseLst[5][i] = colour ... optional, default to 'g' annPolyLst is also a list of lists: annPolyLst[0][i] = list of polygon coords = [[x1,y1], [x2, y2] ...] annPolyLst[1][i] = colour of polygon e.g., 'w' """ # Strip unused dimensions from the array data, header = strip_fits_dims(data, header, 2, 5) # Parse the WCS information w = mkWCSDict(header) wcs = pw.WCS(w['header2D']) # Calculate the image vmin and vmax by measuring the range in the inner # 'scale_frac' of the image s = data.shape boxMaxX = int( s[-1]/2.0 + s[-1] * scaleFrac/2.0 + 1.0 ) boxMinX = int( s[-1]/2.0 - s[-1] * scaleFrac/2.0 + 1.0 ) boxMaxY = int( s[-2]/2.0 + s[-2] * scaleFrac/2.0 + 1.0 ) boxMinY = int( s[-2]/2.0 - s[-2] * scaleFrac/2.0 + 1.0 ) dataSample = data[boxMinY:boxMaxY, boxMinX:boxMaxX] measures = calc_stats(dataSample) sigma = abs(measures['max'] / measures['madfm']) if stretch=='auto': if sigma <= 20: vMin = measures['madfm'] * (-1.5) vMax = measures['madfm'] * 10.0 stretch='linear' elif sigma > 20: vMin = measures['madfm'] * (-3.0) vMax = measures['madfm'] * 40.0 stretch='linear' elif sigma > 500: vMin = measures['madfm'] * (-7.0) vMax = measures['madfm'] * 200.0 stretch='sqrt' if not zMax is None: vMax = max(zMax, measures['max']) if not zMax is None: vMin = zMin # Set the colourscale using an normalizer object normalizer = APLpyNormalize(stretch=stretch, exponent=exponent, vmin=vMin, vmax=vMax) # Setup the figure if fig is None: fig = plt.figure(figsize=(9.5, 8)) ax = fig.add_axes([0.1, 0.08, 0.9, 0.87]) if w['coord_type']=='EQU': ax.set_xlabel('Right Ascension') ax.set_ylabel('Declination') elif w['coord_type']=='GAL': ax.set_xlabel('Galactic Longitude (deg)') ax.set_ylabel('Galactic Latitude (deg)') else: ax.set_xlabel('Unknown') ax.set_ylabel('Unknown') cosY = m.cos( m.radians(w['ycent']) ) aspect = abs( w['ydelt'] / (w['xdelt'] * cosY)) # Set the format of the major tick mark and labels if w['coord_type']=='EQU': f = 15.0 majorFormatterX = FuncFormatter(label_format_hms) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_dms) minorFormattery = None else: f = 1.0 majorFormatterX = FuncFormatter(label_format_deg) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_deg) minorFormattery = None ax.xaxis.set_major_formatter(majorFormatterX) ax.yaxis.set_major_formatter(majorFormatterY) # Set the location of the the major tick marks #xrangeArcmin = abs(w['xmax']-w['xmin'])*(60.0*f) #xmultiple = m.ceil(xrangeArcmin/3.0)/(60.0*f) #yrangeArcmin = abs(w['ymax']-w['ymin'])*60.0 #ymultiple = m.ceil(yrangeArcmin/3.0)/60.0 #majorLocatorX = MultipleLocator(xmultiple) #ax.xaxis.set_major_locator(majorLocatorX) #majorLocatorY = MultipleLocator(ymultiple) #ax.yaxis.set_major_locator(majorLocatorY) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(5)) # Print the image to the axis im = ax.imshow(data, interpolation=interpolation, origin='lower', aspect=aspect, extent=[w['xmax'], w['xmin'], w['ymin'], w['ymax']], cmap=plt.get_cmap(cmapName), norm=normalizer) # Add the colorbar if doColbar: cbar = fig.colorbar(im, pad=0.0) if 'BUNIT' in header: cbar.set_label(header['BUNIT']) else: cbar.set_label('Unknown') if not bunit is None: cbar.set_label(bunit) # Format the colourbar labels - TODO # Set white ticks ax.tick_params(pad=5) for line in ax.xaxis.get_ticklines() + ax.get_yticklines(): line.set_markeredgewidth(1) line.set_color('w') # Create the ellipse source annotations if len(annEllipseLst) > 0: if len(annEllipseLst) >= 5: srcXLst = np.array(annEllipseLst[0]) srcYLst = np.array(annEllipseLst[1]) srcMinLst = np.array(annEllipseLst[2]) srcMajLst = np.array(annEllipseLst[3]) srcPALst = np.array(annEllipseLst[4]) if len(annEllipseLst) >= 6: if type(annEllipseLst[5]) is str: srcEColLst = [annEllipseLst[5]] * len(srcXLst) elif type(annEllipseLst[5]) is list: srcEColLst = annEllipseLst[5] else: rcEColLst = ['g'] * len(srcXLst) else: srcEColLst = ['g'] * len(srcXLst) for i in range(len(srcXLst)): try: el = Ellipse((srcXLst[i], srcYLst[i]), srcMinLst[i], srcMajLst[i], angle=180.0-srcPALst[i], edgecolor=srcEColLst[i], linewidth=lw, facecolor='none') ax.add_artist(el) except Exception: pass # Create the polygon source annotations if len(annPolyLst) > 0: annPolyCoordLst = annPolyLst[0] if len(annPolyLst) > 1: if type(annPolyLst[1]) is str: annPolyColorLst = [annPolyLst[1]] * len(annPolyCoordLst) elif type(annPolyLst[1]) is list: annPolyColorLst = annPolyLst[1] else: annPolyColorLst = ['g'] * len(annPolyCoordLst) else: annPolyColorLst = ['g'] * len(annPolyCoordLst) for i in range(len(annPolyCoordLst)): cpoly = Polygon(annPolyCoordLst[i], animated=False, linewidth=lw) cpoly.set_edgecolor(annPolyColorLst[i]) cpoly.set_facecolor('none') ax.add_patch(cpoly) return fig
def plotfits1(data,header,outFile,scaleFrac=0.9,stretch='linear', exponent=2, cmapName='gist_heat',zmin=None,zmax=None, annEllipseLst=[], annPolyLst=[], annPolyColor='g', lw=1.0, dpi=100, interpolation='Nearest'): """Make a full-size and a thumbnail jpeg image of the file""" outDir,outFileName = os.path.split(outFile) outFileRoot,outExt = os.path.splitext(outFileName) # Strip unused dimensions from the array data,header = strip_fits_dims(data,header,2, 4) # Parse the WCS information wcs = pw.WCS(header) w = mkWCSDict(header) # Calculate the image vmin and vmax by measuring the range in the inner # 'scale_frac' of the image s = data.shape boxMaxX=int((s[-1]/2.0)+(s[-1]*scaleFrac/2.0)+1.0) boxMinX=int((s[-1]/2.0)-(s[-1]*scaleFrac/2.0)+1.0) boxMaxY=int((s[-2]/2.0)+(s[-2]*scaleFrac/2.0)+1.0) boxMinY=int((s[-2]/2.0)-(s[-2]*scaleFrac/2.0)+1.0) vMin = np.nanmin(data[boxMinY:boxMaxY,boxMinX:boxMaxX]) vMax = np.nanmax(data[boxMinY:boxMaxY,boxMinX:boxMaxX]) if zmax: vMax = zmax if zmin: vMin = zmin normalizer = APLpyNormalize(stretch=stretch, exponent=exponent, vmin=vMin, vmax=vMax) #-------------------------------------------------------------------------# # Setup the figure fig = plt.figure(figsize=(9.5,8)) ax = fig.add_subplot(111, position=[0.1,0.08,0.9,0.87]) # Single pane if w['coord_type']=='EQU': ax.set_xlabel('RA (J2000)') ax.set_ylabel('Dec (J2000)') elif w['coord_type']=='GAL': ax.set_xlabel('Galactic Longitude (Deg)') ax.set_ylabel('Galactic Latitude (Deg)') else: ax.set_xlabel('Unknown') ax.set_ylabel('Unknown') cosy = m.cos(m.radians(w['ycent'])) aspect = abs(w['ydelt']/(w['xdelt']*cosy)) # Set the format of the tick mark labels if w['coord_type']=='EQU': f = 15.0 majorFormatterX = FuncFormatter(label_format_hms) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_dms) minorFormattery = None else: f = 1.0 majorFormatterX = FuncFormatter(label_format_deg) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_deg) minorFormattery = None ax.xaxis.set_major_formatter(majorFormatterX) ax.yaxis.set_major_formatter(majorFormatterY) xrangeArcmin = abs(w['xmax']-w['xmin'])*(60.0*f) xmultiple = m.ceil(xrangeArcmin/4.0)/(60.0*f) yrangeArcmin = abs(w['ymax']-w['ymin'])*60.0 ymultiple = m.ceil(yrangeArcmin/4.0)/60.0 majorLocatorX = MultipleLocator(xmultiple) ax.xaxis.set_major_locator(majorLocatorX) majorLocatorY = MultipleLocator(ymultiple) ax.yaxis.set_major_locator(majorLocatorY) # Print the image to the figure im = ax.imshow(data,interpolation=interpolation,origin='lower', aspect=aspect, extent=[w['xmax'],w['xmin'],w['ymin'],w['ymax']], cmap=plt.get_cmap(cmapName),norm=normalizer) # Add the colorbar cbar = fig.colorbar(im ,pad=0.0) cbar.set_label('mJy/beam') # Set white ticks for line in ax.xaxis.get_ticklines(): line.set_color('w') for line in ax.yaxis.get_ticklines(): line.set_color('w') # Create the ellipse source annotations if len(annEllipseLst) > 0: if len(annEllipseLst) >= 5: srcRALst = np.array(annEllipseLst[0]) srcDecLst = np.array(annEllipseLst[1]) srcMinLst = np.array(annEllipseLst[2]) srcMajLst = np.array(annEllipseLst[3]) srcPALst = np.array(annEllipseLst[4]) if len(annEllipseLst) >= 6: if type(annEllipseLst[5]) is str: srcEColLst = [annEllipseLst[5]] * len(srcRALst) elif type(annEllipseLst[5]) is list: srcEColLst = annEllipseLst[5] else: rcEColLst = ['g'] * len(srcRALst) else: srcEColLst = ['g'] * len(srcRALst) for i in range(len(srcRALst)): el = Ellipse((srcRALst[i],srcDecLst[i]), srcMinLst[i], srcMajLst[i], angle=180-srcPALst[i], edgecolor=srcEColLst[i], linewidth=lw, facecolor='none') ax.add_artist(el) # Create the polygon source annotations if len(annPolyLst) > 0: if type(annPolyColor) is str: annPolyColor = [annPolyColor] * len(annPolyLst) elif type(annPolyColor) is list: pass else: annPolyColor =['g'] * len(annPolyLst) for i in range(len(annPolyLst)): cpoly = Polygon(annPolyLst[i], animated=False,linewidth=lw) cpoly.set_edgecolor(annPolyColor[i]) cpoly.set_facecolor('none') ax.add_patch(cpoly) # Save to an image file (full-size & thumbnail images) fig.savefig(outFile, dpi=dpi) plt.close()
# infile = open(curdir +'state_info_revised.csv','r') # csvfile = csv.reader(infile) # for line in csvfile: # lon = (float(line[0]) + float(line[2]))/2 + float(line[5]) # lat = (float(line[1]) + float(line[3]))/2 + float(line[6]) # x, y = m(lon, lat) # name = line[4].replace('\\n', '\n') # plt.text(x, y, name, horizontalalignment='center', verticalalignment='center', fontsize=int(line[7])) for lakepoly in m.lakepolygons: lp = Polygon(lakepoly.boundary, zorder=2) lp.set_facecolor('0.8') lp.set_edgecolor('0.8') lp.set_linewidth(0.1) ax.add_patch(lp) # xx, yy = m(-72.0, 26.0) # plt.text(xx, yy, u'Made by zhyuey', color='yellow') # plt.title('Map of contiguous United States', fontsize=24) # # plt.savefig('usa_state_75.png', dpi=75) # # plt.savefig('usa_state_75.png', dpi=75) # plt.savefig('usa_state_300.png', dpi=300) # # plt.savefig('usa_state_600.png', dpi=600)
def onclick(self,event): # Disable click events if using the zoom & pan modes. if fig.canvas.widgetlock.locked(): return if event.button==1: # Left-click on plot = add a point if axplot.contains(event)[0] and self.mode != 'done': x = event.xdata y = event.ydata self.offsets.append((x,y)) self.points.set_offsets(self.offsets) if len(self.offsets)==1 : axplot.add_collection(self.points) self.update() # Right-click on wedge = halve the lower colour clip if cbar.ax.contains(event)[0]: clims = cax.get_clim() cax.set_clim(clims[0]/2.0,clims[1]) self.update() elif event.button==2: # Middle-click = delete last created point if axplot.contains(event)[0] and len(self.offsets)>0 \ and self.mode != 'done': self.offsets.pop(-1) if len(self.offsets)==0: self.points.remove() else: self.points.set_offsets(self.offsets) self.update() # Middle-click on wedge = reset the colour clip if cbar.ax.contains(event)[0]: clims = cax.get_clim() cax.set_clim(zmin,zmax) self.update() if event.button==3: # Right-click on plot = complete the polygon if axplot.contains(event)[0] and len(self.offsets)>2 \ and self.mode != 'done': cpoly = Polygon(self.offsets, animated=False,linewidth=2.0) if self.mode == 'src': cpoly.set_edgecolor('white') cpoly.set_facecolor('none') elif self.mode == 'sky': cpoly.set_edgecolor('yellow') cpoly.set_facecolor('none') elif self.mode == 'exc': cpoly.set_edgecolor('black') cpoly.set_facecolor('none') self.apertures.append(axplot.add_patch(cpoly)) self.update('complete') # Left-click on wedge = halve the upper colour clip if cbar.ax.contains(event)[0]: clims = cax.get_clim() cax.set_clim(clims[0],clims[1]/2.0) self.update()
def step_plots(self): """ Save each step frame to: outdir/frames/frame_00000.png outdir/frames/frame_00001.png etc. And generate GIF in outdir/plan_movie.gif Inputs: Nothing Returns: Nothing """ if self.verbose: print("Generating step-by-step plots.") # # Make frame directory if necessary # outdir = os.path.join(self.outdir, 'frames') if not os.path.exists(outdir): os.mkdir(outdir) # # Base frame is portal map with agent locations # num_links = 0 num_fields = 0 num_ap = len(self.plan.portals)*_AP_PER_PORTAL fig, ax = self.make_portal_fig() drawn_agents = [] agents_last_pos = [] frames = [] for agent in range(self.plan.num_agents): # # Find agent's first location # for ass in self.plan.assignments: if ass['agent'] == agent: break else: raise ValueError("Could not find agent {0} in " "assignments".format(agent)) portal_idx = ass['location'] agents_last_pos.append(portal_idx) xpos = self.plan.portals_mer[portal_idx, 0] ypos = self.plan.portals_mer[portal_idx, 1] drawn_agents.append( ax.text(xpos, ypos, 'A{0}'.format(agent+1), bbox={'facecolor':'magenta', 'alpha':0.5, 'pad':1}, fontweight='bold', ha=self.agent_ha[portal_idx], va=self.agent_va[portal_idx], fontsize=12, zorder=12)) ax.set_title('Time: 00:00:00 Links: 0 Fields: 0 ' 'AP: {0:>7d}'.format(num_ap), fontsize=18) fname = os.path.join(outdir, 'frame_00000.png') fig.savefig(fname, dpi=300) frames.append(fname) # # Group assignments by arrival time, and plot each arrival # time actions as a single frame. # arrivals = list(set([ass['arrive'] for ass in self.plan.assignments])) arrivals.sort() # # Plot agent movements, links, and fields # frame = 1 for arrival in arrivals: # # Get the assignments happening at this arrival time # my_ass = [ass for ass in self.plan.assignments if ass['arrive'] == arrival] # # Determine if agents moved since last frame # drawn_lines = [] for ass in my_ass: last_origin = agents_last_pos[ass['agent']] this_origin = ass['location'] if last_origin == this_origin: # did not move continue # # Draw movement line # line, = ax.plot([self.plan.portals_mer[last_origin, 0], self.plan.portals_mer[this_origin, 0]], [self.plan.portals_mer[last_origin, 1], self.plan.portals_mer[this_origin, 1]], linestyle='--', color='magenta', lw=2) drawn_lines.append(line) # # Update agent position # drawn_agents[ass['agent']].remove() drawn_agents[ass['agent']] = \ ax.text(self.plan.portals_mer[this_origin, 0], self.plan.portals_mer[this_origin, 1], 'A{0}'.format(ass['agent']+1), bbox={'facecolor':'magenta', 'alpha':0.5, 'pad':1}, fontweight='bold', ha=self.agent_ha[portal_idx], va=self.agent_va[portal_idx], fontsize=12, zorder=12) agents_last_pos[ass['agent']] = this_origin # # If at least one agent moved, save frame and remove # movement lines # if drawn_lines: # # Update title, save # hr = arrival // 3600 mn = (arrival-hr*3600) // 60 sc = (arrival-hr*3600-mn*60) ax.set_title('Time: {0:02d}:{1:02d}:{2:02d} ' 'Links: {3:>4d} Fields: {4:>4d} ' 'AP: {5:>7d}'. format(hr, mn, sc, num_links, num_fields, num_ap), fontsize=18) fname = os.path.join(outdir, 'frame_{0:05d}.png'. format(frame)) frame += 1 fig.savefig(fname, dpi=300) frames.append(fname) # # Remove drawn lines # for line in drawn_lines: line.remove() # # Draw links and fields, new fields are red # fields_patches = [] fields_drawn = [] for ass in my_ass: link = (ass['location'], ass['link']) ax.plot(self.plan.portals_mer[link, 0], self.plan.portals_mer[link, 1], color=self.color, lw=2) num_links += 1 num_ap += _AP_PER_LINK for fld in self.plan.graph.edges[link]['fields']: coords = [self.plan.portals_mer[i] for i in fld] patch = Polygon(coords, facecolor='red', alpha=0.3, edgecolor='none') fields_patches.append(patch) fields_drawn.append(ax.add_patch(patch)) num_fields += 1 num_ap += _AP_PER_FIELD # # Update title, save # hr = arrival // 3600 mn = (arrival-hr*3600) // 60 sc = (arrival-hr*3600-mn*60) ax.set_title('Time: {0:02d}:{1:02d}:{2:02d} ' 'Links: {3:>4d} Fields: {4:>4d} ' 'AP: {5:>7d}'. format(hr, mn, sc, num_links, num_fields, num_ap), fontsize=18) fname = os.path.join(outdir, 'frame_{0:05d}.png'. format(frame)) frame += 1 fig.savefig(fname, dpi=300) frames.append(fname) # # Remove red patch, update to color and re-add # for patch, drawn in zip(fields_patches, fields_drawn): drawn.remove() patch.set_facecolor(self.color) ax.add_patch(patch) plt.close(fig) if self.verbose: print("Frames saved to: {0}/".format(outdir)) # # Generate GIF # fname = os.path.join(self.outdir, 'plan_movie.gif') with imageio.get_writer(fname, mode='I', duration=0.5) as writer: for frame in frames: image = imageio.imread(frame) writer.append_data(image) optimize(fname) if self.verbose: print("GIF saved to {0}".format(fname)) print()
circle.set_linewidth(3) circle.set_facecolor(None) patches = [circle] for i in range(nPolys): p = [1] + [0] * (n - 1) + [-z[i]] roots = np.roots(p) angles = np.sort([cmath.phase(root) for root in roots]) roots = np.cos(angles) + j * np.sin(angles) x = roots.real y = roots.imag coords = np.stack((x, y), axis=1) poly = Polygon(xy=coords, closed=True) poly.set_edgecolor('royalblue') poly.set_facecolor('lightsteelblue') poly.set_linewidth(1) patches.append(poly) fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}) # Set bottom and left spines as x and y axes of coordinate system ax.spines['bottom'].set_position('zero') ax.spines['left'].set_position('zero') # Remove top and right spines ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # Create 'x' and 'y' labels placed at the end of the axes ax.set_xlabel('x', size=14, labelpad=-24, x=1.03) ax.set_ylabel('y', size=14, labelpad=-21, y=1.02, rotation=0)
def plot_elevation(lons, lats, elevation, cmap="Reds_r", levels=None, inset_bounds=None): """ Create a contour plot, usually for elevation data. Given longitudes, latitudes, and elevation data, create a filled contour of the data. The data should be regularly gridded. A colorbar for the plot is also created. Optionally, you can make an inset of a region of interest. Parameters ---------- lons : array An N-element array of longitudes of the data lats : array An M-element array of latitudes of the data elevation : array An NxM-element array of the elevation of the data. The first dimension corresponds to the lons , and the second dimension corresponds to the lats . cmap : str, optional A named colormap name from Matplotlib. Default is to use Reds_r. levels : array, optional The levels to be contoured. By default, 10 levels spanning the min/max of the elevation will be used. inset : boolean, optional If True, an inset plot is also created. inset_bounds: array, optional The inset_bounds is a 4 element array-like value (e.g., an array, list, or tuple) in the order of [lon_min, lon_max, lat_min, lat_max]. By default, None which means no inset_bounds has been set thus no inset will be created. Returns ------- SimpleNamespace Returned value has several keys, some of which are optionally included. :contour: Matplotlib QuadContourSet :colorbar: Matplotlib Colorbar class :inset_bounds: Matplotlib QuadContourSet (if inset_bounds is requested) :polygon: Matplotlib Polygon (if inset_bounds is requested) The polygon of the inset.:lines: A list of Matplotlib CollectionPatch-es (if inset_bounds is requested) Examples ------- >>> from scipy.stats import multivariate_normal >>> import numpy as np # Generate some lats and lons >>> lons = np.arange(100) >>> lats = np.arange(100) # Make these 2D "coordinate" arrays >>> lons2d, lats2d = np.meshgrid(lons, lats) # Fill in coordinates to find the 2D Gaussian PDF >>> coord = np.empty(lons2d.shape + (2,)) >>> coord[:, :, 0] = lons2d >>> coord[:, :, 1] = lats2d >>> mean = [1, -2] # coordinates of Gaussian peak >>> cov = [[5.0, 0], [0.0, 20.0]] # covariance array - width of peak # Generate the elevation data >>> rv = multivariate_normal(mean, cov) >>> data = rv.pdf(coord) >>> data = data/np.max(data)*400 # scale the data >>> elv_plot = plot_elevation(lons, lats, data) # Pick some new levels >>> elv_plot2 = plot_elevation(lons, lats, data, levels = np.arange(0, 300, 50)) """ import matplotlib.colors as mplcol from matplotlib.patches import Polygon, ConnectionPatch import numpy as np all_plots = SimpleNamespace() # all plots are added to this to be returned ##Pick levels for contour: if levels is None: levels = np.linspace(np.nanmin(elevation), np.nanmax(elevation), 10) # Build the color map, based on a Matplotlib colormap. # Get two extra colors for extending colors to the min _and_ max colors = plt.cm.get_cmap(cmap)(np.linspace(0, 1, levels.size + 2)) # The new color map for the levels cmap_mod = mplcol.ListedColormap(colors[1:-1, :]) # Set the min/max (under/over) for the extended colorbar cmap_mod.set_over(colors[-1, :]) cmap_mod.set_under(colors[0, :]) # Pack these up into a dictionary for the contour plot, # and add extending contours to min and max contourProps = {'levels': levels, 'cmap': cmap_mod, 'extend': 'both'} ##Plot the elevation contour ##**contourProps: keyword extension fig, ax = plt.subplots(figsize=(8, 6), dpi=100) c_big = ax.contourf(lons, lats, elevation, **contourProps) all_plots.contour = c_big ##Make the colorbar cb = c_big.ax.figure.colorbar(c_big) all_plots.colorbar = cb ##Make an inset if inset_bounds is not None: print("You have requested an inset: [lon_min, lon_max]=", inset_bounds[:2], " [lat_min, lat_max]=", inset_bounds[-2:]) # Set the corners of the polygon #lat_poly = [34.65, 34.85] lat_poly = inset_bounds[-2:] #lon_poly = [-86.65, -86.45] lon_poly = inset_bounds[:2] # Define the vertices for the polygon lat_vert = [lat_poly[0], lat_poly[1], lat_poly[1], lat_poly[0]] lon_vert = [lon_poly[0], lon_poly[0], lon_poly[1], lon_poly[1]] lon_lat = np.column_stack((lon_vert, lat_vert)) # Draw the polygon poly = Polygon(lon_lat) _null = c_big.ax.add_patch(poly) poly.set_facecolor('none') poly.set_edgecolor('black') all_plots.polygon = poly # add the polygon pass # Make the inset contour newax = c_big.ax.figure.add_axes([0, 0, 0.5, 0.25]) c_inset = newax.contourf(lons, lats, elevation, **contourProps) all_plots.inset = c_inset # add the inset # Get the corners of the "big" contour ll, ul, lr, ur = c_big.ax.get_position().corners() # Set the width and height of the inset, and position it # inset_width = (inset_bounds[1] - inset_bounds[0])/3.0 # inset_height = (inset_bounds[3] - inset_bounds[2])/3.0 inset_width = 0.2 inset_height = 0.15 new_pos = [lr[0] - inset_width, lr[1], inset_width, inset_height] c_inset.ax.set_position(new_pos) # Next, "zoom" for the inset: _new_lim = c_inset.ax.set_xlim(lon_poly) _new_lim = c_inset.ax.set_ylim(lat_poly) # Modify ticks of the inset c_inset.ax.tick_params(labelbottom=False, labelleft=False) c_inset.ax.tick_params(bottom=False, left=False) # Finally, add the lines. # Get the lower left/upper right of the polygon and inset ll_poly = [lon_poly[0], lat_poly[0]] ur_poly = [lon_poly[1], lat_poly[1]] ll_inset, _, _, ur_inset = c_inset.ax.get_position().corners() # Now, add the lines patch_props = { 'coordsA': 'data', 'axesA': c_big.ax, 'coordsB': 'figure fraction', 'axesB': c_inset.ax } line1 = ConnectionPatch(xyA=ll_poly, xyB=ll_inset, **patch_props) _null = c_big.ax.add_patch(line1) line2 = ConnectionPatch(xyA=ur_poly, xyB=ur_inset, **patch_props) _null = c_big.ax.add_patch(line2) all_plots.lines = [line1, line2] return all_plots pass
lines = LineCollection(segs,antialiaseds=(1,)) lines.set_facecolors(np.random.rand(3, 1) * 0.5 + 0.5) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) cnt += 1 infile = open(curdir +'state_info_revised.csv','r') csvfile = csv.reader(infile) for lakepoly in m.lakepolygons: lp = Polygon(lakepoly.boundary, zorder=3) lp.set_facecolor(thisblue) lp.set_linewidth(0.1) ax.add_patch(lp) for line in csvfile: lon = (float(line[0]) + float(line[2]))/2 + float(line[5]) lat = (float(line[1]) + float(line[3]))/2 + float(line[6]) x, y = m(lon, lat) name = line[4].replace('\\n', '\n') plt.text(x, y, name, horizontalalignment='center', verticalalignment='center', fontsize=int(line[7])) xx, yy = m(-72.0, 26.0) plt.text(xx, yy, u'Made by zhyuey', color='yellow') plt.title('Map of contiguous United States', fontsize=24)
segs = [] for i in range(1,len(shape.parts)): index = shape.parts[i-1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) lines = LineCollection(segs,antialiaseds=(1,)) lines.set_facecolors(np.random.rand(3, 1) * 0.5 + 0.5) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) for lakepoly in m.lakepolygons: lp = Polygon(lakepoly.boundary) lp.set_facecolor('#0000aa') ax.add_patch(lp) # m.drawrivers(linewidth=0.5, zorder = 3, color='blue') lon = (float(line[0]) + float(line[2]))/2 + float(line[5]) lat = (float(line[1]) + float(line[3]))/2 + float(line[6]) x, y = m(lon, lat) name = line[4].replace('\\n', '\n') plt.text(x, y, name, horizontalalignment='center', verticalalignment='center', fontsize=24) filename = sys.path[0] + '/state_img/m_' + line[4] + '.png' print(filename)