def load_colorado_shapes(m): # read all US counties rdr = shapefile.Reader("../USA_adm/USA_adm2") shapes = rdr.shapes() records = rdr.records() # only keep Colorado counties ndx = filter(lambda i: records[i][4] == 'Colorado', np.arange(len(shapes))) shapes = [shapes[i] for i in ndx] records = [records[i] for i in ndx] # modified from web tutorial # http://www.geophysique.be/2013/02/12/matplotlib-basemap-tutorial-10-shapefiles-unleached-continued/ line_col = [] for record, shape in zip(records, shapes): lons,lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [data,] else: 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_edgecolors('k') lines.set_linewidth(0.8) line_col.append(lines) return line_col
def addLine(shapefilename): r = shapefile.Reader(shapefilename) shapes = r.shapes() records = r.records() cnt = 0 for record, shape in zip(records, shapes): print(cnt) lons,lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [data,] else: 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,), zorder=3) # lines.set_facecolors(np.random.rand(3, 1) * 0.5 + 0.5) lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) cnt += 1
def plot_dt(DT, ax=None): segs = [] weights = [] # this is a proper iterator for face, idx in DT.finite_edges(): if DT.is_constrained((face, idx)): weight = 3 else: weight = 1 weights.append(weight) vert1 = face.vertex((idx + 1) % 3) vert2 = face.vertex((idx + 2) % 3) seg = [[vert1.point().x(), vert1.point().y()], [vert2.point().x(), vert2.point().y()]] segs.append(seg) coll = LineCollection(segs) colors = cm.jet(np.random.random(len(segs))) coll.set_edgecolors(colors) coll.set_linewidths(weights) ax = ax or plt.gca() ax.add_collection(coll) ax.axis('equal') return coll
def traceShape(file_shapefile): r = shapefile.Reader(file_shapefile) shapes = r.shapes() records = r.records() #sc_fac = 100000 for record, shape in zip(records,shapes): #print shape.points lonsh,latsh = zip(*shape.points) # lonsh = [x/sc_fac for x in lonsh] # latsh = [x/sc_fac for x in latsh] data = np.array(m(lonsh, latsh)).T if len(shape.parts) == 1: segs = [data,] else: 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(cm.jet(np.random.rand(1))) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) return None
def plot_view(result): # Determine bounding box if no clipping boundary was supplied if not result['bbox']: result['bbox'] = bbox_of_view(result) ax = plt.subplot(111) # plt.box(on=None) m = Basemap(resolution='i', projection='merc', llcrnrlat=result['bbox']['ymin'], urcrnrlat=result['bbox']['ymax'], llcrnrlon=result['bbox']['xmin'], urcrnrlon=result['bbox']['xmax'], lat_ts=(result['bbox']['xmin'] + result['bbox']['xmax']) / 2) m.drawcoastlines() try: for el in result['results']: vectors = get_vectors_from_postgis_map(m, loads(el['geom'])) lines = LineCollection(vectors, antialiaseds=(1, )) lines.set_facecolors('black') lines.set_edgecolors('white') lines.set_linewidth(1) ax.add_collection(lines) m.fillcontinents(color='coral', lake_color='aqua') # If AttributeError assume geom_type 'Point', simply collect all # points and perform scatterplot except AttributeError: xy = m([loads(point['geom']).x for point in result['results']], [loads(point['geom']).y for point in result['results']]) plt.scatter(xy[0], xy[1]) plt.show()
def add_data(globe, axes, color_dict): """Add shapefile polygons to the matplotlib axes""" file_object = shapefile.Reader(filename) shapes = file_object.shapes() records = file_object.records() #iterate over all but the first 20 polygons (they're junk) for record, shape in zip(records[20:],shapes[20:]): #this entry is the colour code description = record[6] lons,lats = zip(*shape.points) #transform the lat/long coords to the right projection data = np.array(globe(lons, lats)).T #shapefile shapes can have disconnected parts, we have #to check if len(shape.parts) == 1: segs = [data,] else: segs = [] for i in range(1,len(shape.parts)): #add all the parts index = shape.parts[i-1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) #Add all the parts we've found as a set of lines lines = LineCollection(segs,antialiaseds=(1,)) lines.set_facecolors(color_dict[description]) lines.set_edgecolors('k') lines.set_linewidth(0.1) #add the collection to the active axes axes.add_collection(lines)
def draw_line(self, segments, ax, **kwargs): key = (ax, kwargs.pop('key', self.keyfor(segments))) ec = kwargs.pop('ec', 'k') t = kwargs.pop('transform', None) zorder = kwargs.pop('zorder', 1) if key not in self.items: l = LineCollection(segments) ax.add_collection(l) self.items[key] = dict(lines=l) d = self.items[key] l = d['lines'] l.set_segments(segments) l.set_edgecolors(ec) if t is not None: l.set_transform(mplt.Affine2D(matrix=t) + ax.transData) # u += drawer.draw_line( # np.array([ # [0,10], # [0,10] # ]).T.reshape(1,2,2), # ax # ) return l,
def draw_shp_polygons(self, shp_filepath, linewidths=0.2, colors='k', antialiaseds=None, linestyles='solid'): """ Draw a shapefile containing polygons """ # Read the shapefile as shapes and records. For each polygon in shapes, draw its boundaries r = shapefile.Reader(shp_filepath) shapes = r.shapes() records = r.records() for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) data = [(x, y) for x, y in zip(*self(lons, lats))] # shape.parts is a list containing the starting index of each part of shape (e.g. a lake inside the shape) on xy_pts. If shape contains only 1 part, a list containing 0 is returned. if len(shape.parts) == 1: segs = [data, ] else: segs = [] for npart in range(1, len(shape.parts)): ix1 = shape.parts[npart-1] ix2 = shape.parts[npart] segs.append(data[ix1:ix2]) segs.append(data[ix2: ]) lines = LineCollection(segs, antialiaseds = [1, ]) lines.set_edgecolors(colors) lines.set_linestyle(linestyles) lines.set_linewidth(linewidths) self.ax.add_collection(lines)
def plot(self, ax=None, cmapname=None, cmap=None, linewidth=1, edgecolor='grey', facecolor=None, alpha=1): """Plot the geometries on the basemap using the defined colors Parameters: ----------- ax : matplotlib.axis object An axis object for plots. Overwrites the self.ax attribute. cmapname : string Name of the color map from matplotlib (LINK!) (default: 'seismic') cmap : matplotlib colormap You can create you own colormap and pass it to the plot. linewidth : float Width of the lines. edgecolor : string, float or iterable Definition of the edge color. Can be an iterable with a color definition for each geometry, a string with one color for all geometries or a float to define one color for all geometries from the cmap. facecolor : string, float or iterable Definition of the face color. See edgecolor. alpha : float Level of transparency. """ if ax is not None: self.ax = ax n = 0 if facecolor is None: facecolor = self.color if edgecolor is None: edgecolor = self.color if cmapname is not None: self.cmapname = cmapname if self.data is not None: self.data = np.array(self.data) if cmap is None: cmap = plt.get_cmap(self.cmapname) for geo in self.geometries: vectors = self.get_vectors_from_postgis_map(geo) lines = LineCollection(vectors, antialiaseds=(1, )) lines.set_facecolors(self.select_color(facecolor, cmap, n)) lines.set_edgecolors(self.select_color(edgecolor, cmap, n)) lines.set_linewidth(linewidth) lines.set_alpha(alpha) self.ax.add_collection(lines) n += 1
def draw_map(dpts_dataframe, topic_index): m, ax = carte_france() departements = 'data/DEPARTEMENT/DEPARTEMENT.shp' shp = departements r = shapefile.Reader(shp) shapes = r.shapes() records = r.records() records = clean_records(records) done = False for record, shape in zip(records, shapes): geo_points = [lambert932WGPS(x, y) for x, y in shape.points] lons = [_[0] for _ in geo_points] lats = [_[1] for _ in geo_points] data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [ data, ] else: # un polygone est une liste de sommets # on le transforme en une liste d'arêtes 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, )) # pour changer les couleurs c'est ici, il faudra utiliser le champ records # pour les changer en fonction du nom du départements if not done: for i, _ in enumerate(record): print(i, _) done = True # dep = retourne_vainqueur(record[2]) dep = True if dep is not None: couleur = colors[int(dpts_dataframe['code_couleur'].loc[ dpts_dataframe[0] == int(record[1])].values[0]), :] lines.set_facecolors(couleur) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) else: print("--- issue with", record[-1]) plt.savefig('heatmaps/heatmap_topic' + str(topic_index) + '.png')
def plot_map(year, disease, color_parameter, std_num_records): mpl.rcParams['font.size'] = 10. mpl.rcParams['font.family'] = 'Comic Sans MS' mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. fig = plt.figure(figsize=(11.7, 8.3)) plt.style.use('fivethirtyeight') plt.subplots_adjust(left=0.05, right=0.95, top=0.90, bottom=0.05, wspace=0.15, hspace=0.05) ax = plt.subplot(111) m = Basemap(resolution='i', projection='merc', llcrnrlon=-132, llcrnrlat=22, urcrnrlon=-60, urcrnrlat=50) m.etopo() m.drawcountries() for record, shape, num in zip(records, shapes, std_num_records): lons, lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [ data, ] else: 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, )) color = colors.hsv_to_rgb((color_parameter, num, 1)) lines.set_facecolor(color) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) m.drawstates(linewidth=0.5) m.drawcoastlines(linewidth=0.5) plt.title('geo-heatmap for {} in {}'.format(disease, year)) plt.savefig('geo-heatmap for {} in {}.pdf'.format(disease, year))
def plot_countries(countries, world): if type(countries) != list: countries = [countries] ax = plt.subplot(111) m = get_region_map(countries, world) for country in countries: shpsegs = [] for ring in country['SHAPE']: x, y = geo2map_coord(ring, m) shpsegs.append(zip(x,y)) lines = LineCollection(shpsegs,antialiaseds=(1,)) lines.set_facecolors(cm.jet(np.random.rand(1))) lines.set_edgecolors('k') #lines.set_linewidth(0.3) ax.add_collection(lines) plt.show()
def plotclustering(label, zipcodes, nameee): # print len(zipcodes) label = np.array(label) zipcodes = np.array(zipcodes) cluster1 = zipcodes[label == 1] cluster2 = zipcodes[label == 2] cluster0 = zipcodes[label == 0] cluster3 = zipcodes[label == 3] fig = plt.figure(figsize =(15, 15)) ax = plt.subplot(111) lllat = 40.473; urlat = 40.93; lllon = -74.27; urlon = -73.69 # define the boundary of the map m = Basemap(ax=ax, projection = 'stere', lon_0 = (urlon + lllon)/2, lat_0 = (urlat +lllat)/2, llcrnrlon = lllon, llcrnrlat = lllat, urcrnrlon = urlon, urcrnrlat = urlat, resolution= 'l')# create the basemap # m.drawcoastlines() m.drawcountries() shp = ShapeFile('c:/Users/gang/Desktop/nyczipregion') dbf = dbflib.open('c:/Users/gang/Desktop/nyczipregion') for npoly in range(shp.info()[0]): shpsegs = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons , lats = zip(*verts[ring]) x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring ==0: shapedict = dbf.read_record(npoly) name = shapedict['Zcta5ce00'] lines = LineCollection(shpsegs, antialiaseds=(1,)) if name in cluster0: lines.set_facecolors('b') if name in cluster1: lines.set_facecolors('g') if name in cluster2: lines.set_facecolors('r') if name in cluster3: lines.set_facecolors('y') lines.set_alpha(1) lines.set_edgecolors('k') ax.add_collection(lines) plt.title('Box Clustering Based On Taxi Trips') plt.savefig(nameee+'_box_trip_Clustering.png', dpi=300) plt.show()
def mapcountries(countries): #Map list of countries? from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt fig = plt.figure(figsize=(11.7, 8.3)) plt.subplots_adjust() m = Basemap(projection='hammer', resolution=None, lon_0=0) m.drawcountries(linewidth=0.5) m.drawcoastlines(linewidth=0.5) from shapelib import ShapeFile import dbflib from matplotlib.collections import LineCollection from matplotlib import cm #for ctry in countries: shp = ShapeFile(r"borders/world_adm1") dbf = dbflib.open(r"borders/world_adm1") for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_obj(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min( lats) < -91.: raise ValueError('Lats/Lons out of range') x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring == 0: shapedict = dbf.read_record(npoly) name = shapedict["NAME_1"] shapedict['RINGNUM'] = ring + 1 shapedict['SHAPENUM'] = npoly + 1 shpinfo.append(shapedict) print(name) lines = LineCollection(shpsegs, antialiaseds=(1, )) lines.set_facecolors(cm.jet(0.5)) lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) plt.show()
def algo (region,output, word): reg = [0 for i in range(0,23)] total = 0 for line in region: #reg_num number items = line.rstrip('\n').split('\t') reg[int(items[0])]=int(items[1]) total = total+int(items[1]) reg=np.array(reg) max_percent=np.max(reg) plt.figure(figsize=(15,15)) ax = plt.subplot(111) m = Basemap(projection='merc', lat_0=45, lon_0=0, resolution = 'h', area_thresh = 10.0, llcrnrlat=41.33, llcrnrlon=-5, urcrnrlat=51.5, urcrnrlon=9.7) m.drawcoastlines() #m.drawcountries() # french border does not fit with region ones m.fillcontinents(color='lightgrey',lake_color='white') m.drawmapboundary(fill_color='white') sf = shapefile.Reader("./geodata/FRA_adm1") shapes = sf.shapes() records = sf.records() for record, shape in zip(records,shapes): lons,lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [data,] else: 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_edgecolors('k') lines.set_linewidth(0.5) lines.set_facecolors('brown') lines.set_alpha(float(reg[record[3]])/max_percent) #record[3] est le numero de region ax.add_collection(lines) plt.savefig(word+'-'+str(total)+'.png',dpi=300) return 0
def plotCountry(m, ax, id, path='gadm0'): country, lonlat = merged[id] r = shapefile.Reader(r"%s/%s_adm0" % (path, country)) shapes = r.shapes() records = r.records() for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [ data, ] else: 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('lightgreen') lines.set_edgecolors('k') lines.set_linewidth(0.1) lines.set_alpha(0.5) ax.add_collection(lines) # Add country centroid lon, lat = lonlat xpt, ypt = m(lon, lat) txt = ax.annotate(id, (xpt, ypt), color='r', size='medium', ha='center', va='center', path_effects=[ PathEffects.withStroke(linewidth=3, foreground="w"), PathEffects.withSimplePatchShadow() ])
def drawcountry(self, ax, base_map, iso2, color, alpha = 1): if iso2 not in self.countries: raise ValueError, "Where is that country ?" vertices = self.countries[iso2] shape = [] for vertex in vertices: longs, lats = zip(*vertex) # conversion to plot coordinates x,y = base_map(longs, lats) shape.append(zip(x,y)) lines = LineCollection(shape,antialiaseds=(1,)) lines.set_facecolors(cm.hot(np.array([color,]))) lines.set_edgecolors('white') lines.set_linewidth(0.5) lines.set_alpha(alpha) ax.add_collection(lines)
def polyPlotShapeFile(m, ax, sf, crs): import numpy as np import pyproj from matplotlib.collections import LineCollection from matplotlib import cm import matplotlib.pyplot as plt shapes = sf.shapes() records = sf.records() shp_proj = pyproj.Proj(crs.to_proj4()) #.shp file projection std_proj = pyproj.Proj(init='epsg:4326') # Lat/Lon system for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) lons, lats = pyproj.transform(shp_proj, std_proj, lons, lats) data = np.array(m(lons, lats)).T if record['POLY_TYPE'] == 'I': if len(shape.parts) == 1: segs = [ data, ] else: 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, ), zorder=1, alpha=0.2) lines.set_facecolors('b') # lines.set_facecolors(cm.jet(np.random.rand(1))) lines.set_edgecolors('k') lines.set_linewidth(1) ax.add_collection(lines)
def plot_europe_map(country_weights, b=None, ax=None): """ Plot a map from shapefiles with coutnries colored by gamma. Inspired by Magnus. """ if ax == None: ax = plt.subplot(111) m = Basemap(llcrnrlon=-10., llcrnrlat=30., urcrnrlon=50., urcrnrlat=72., projection='lcc', lat_1=40., lat_2=60., lon_0=20., resolution='l', area_thresh=1000., rsphere=(6378137.00, 6356752.3142)) m.drawcoastlines(linewidth=0) r = shapefile.Reader(r'settings/ne_10m_admin_0_countries/ne_10m_admin_0_countries') all_shapes = r.shapes() all_records = r.records() shapes = [] records = [] for country in all_countries: shapes.append(all_shapes[shapefile_index[country]]) records.append(all_records[shapefile_index[country]]) country_count = 0 for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [data, ] else: 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_facecolor(cmap(country_weights[country_count])) lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) country_count += 1 if b: plt.text(1.5e5, 4e6, r'$\beta = ' + str(b) + r'$', fontsize=12)
def draw_shp_polygons(self, shp_filepath, linewidths=0.2, colors='k', antialiaseds=None, linestyles='solid'): """ Draw a shapefile containing polygons """ # Read the shapefile as shapes and records. For each polygon in shapes, draw its boundaries r = shapefile.Reader(shp_filepath) shapes = r.shapes() records = r.records() for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) data = [(x, y) for x, y in zip(*self(lons, lats))] # shape.parts is a list containing the starting index of each part of shape (e.g. a lake inside the shape) on xy_pts. If shape contains only 1 part, a list containing 0 is returned. if len(shape.parts) == 1: segs = [ data, ] else: segs = [] for npart in range(1, len(shape.parts)): ix1 = shape.parts[npart - 1] ix2 = shape.parts[npart] segs.append(data[ix1:ix2]) segs.append(data[ix2:]) lines = LineCollection(segs, antialiaseds=[ 1, ]) lines.set_edgecolors(colors) lines.set_linestyle(linestyles) lines.set_linewidth(linewidths) self.ax.add_collection(lines)
def draw_map(x1=6., x2=11., y1=45., y2=48.): ### PARAMETERS FOR MATPLOTLIB : import matplotlib as mpl mpl.rcParams['font.size'] = 10. mpl.rcParams['font.family'] = 'Bitstream Vera Sans' mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. #fig = plt.figure(figsize=(11.7,8.3)) #Custom adjust of the subplots plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(resolution='i',projection='merc', llcrnrlat=y1,urcrnrlat=y2,llcrnrlon=x1,urcrnrlon=x2,lat_ts=(x1+x2)/2) m.drawcountries(linewidth=0.5) m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(y1,y2,2.),labels=[1,0,0,0],color='black',dashes=[1,1],labelstyle='+/-',linewidth=0.2) # draw parallels m.drawmeridians(np.arange(x1,x2,2.),labels=[0,0,0,1],color='black',dashes=[1,1],labelstyle='+/-',linewidth=0.2) # draw meridians m.bluemarble() r = shapefile.Reader(r"borders/CHE_adm3") shapes = r.shapes() records = r.records() for record, shape in zip(records,shapes): lons,lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [data,] else: 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(cm.jet(np.random.rand(1))) lines.set_edgecolors('k') lines.set_linewidth(0.05) ax.add_collection(lines) return (plt, m)
def get_rivers(mmap=None): import shapefile # from matplotlib.patches import Polygon from matplotlib.collections import LineCollection shf = '/home/raul/Github/basemap_shaded/sonoma_rivers/sonoma_rivers' s = shapefile.Reader(shf) shapes = s.shapes() Nshp = len(shapes) segs = [] for n in range(Nshp): pts = shapes[n].points lons, lats = zip(*pts) x, y = mmap(lons, lats) segs.append(zip(x, y)) lines = LineCollection(segs) lines.set_edgecolors('b') lines.set_linewidth(1) return lines
def plotlines(m, ax=plt.gca(), path='', rotate=False): ''' function to plot grounding and coast line around Antarctica on a Basemap, based on the MODIS mosaik project 2009. Try not to define the Basemap more often than necessary to speed things up. ''' if not hasattr(m, 'Grounding_Line'): #check if it has already been loaded print('loading grounding line') if path: glpath = path else: glpath = '/home/andi/home_zmaw/phd/programme/surfacetypes/' m.readshapefile(shapefile=glpath+'moa_2009_groundingline_v11', \ name='Grounding_Line', drawbounds=False) m.readshapefile(shapefile=glpath+'moa_2009_islands_v11',\ name='Grounding_Line_Islands', drawbounds=False) m.readshapefile(shapefile=glpath+'moa_2009_coastline_v11', \ name='Coast_Line', drawbounds=False) if rotate: #this takes forever! print('get yourself some coffee ...') Coast_line_r = [] for x_tmp, y_tmp in m.Coast_Line[0]: Coast_line_r.append((y_tmp, x_tmp)) Grounding_Line_r = [] for x_tmp, y_tmp in m.Grounding_Line[0]: Grounding_Line_r.append((y_tmp, x_tmp)) Grounding_Line_Islands_r = [] for x_tmp, y_tmp in m.Grounding_Line_Islands[0]: Grounding_Line_Islands_r.append((y_tmp, x_tmp)) Cline = LineCollection([Coast_line_r]) gline = LineCollection([Grounding_Line_r]) g2line = LineCollection([Grounding_Line_Islands_r]) else: Cline = LineCollection(m.Coast_Line) gline = LineCollection(m.Grounding_Line) g2line = LineCollection(m.Grounding_Line_Islands) Cline.set_edgecolors( 'k' ) #set to other color if you want to distinguish between coast line and grounding line Cline.set_linewidth(2) ax.add_collection(Cline) gline.set_edgecolors('k') gline.set_linewidth(2) ax.add_collection(gline) g2line.set_edgecolors('k') g2line.set_linewidth(2) ax.add_collection(g2line)
class SunPlotPy(wx.Frame, Spatial, Grid ): """ The main frame of the application """ title = 'sunplot(py)' # Plotting options autoclim=True showedges=False bgcolor='k' textcolor='w' cmap='RdBu' particlesize = 1.8 particlecolor = 'm' # other flags collectiontype='cells' oldcollectiontype='cells' # tindex=0 depthlevs = [0., 10., 100., 200., 300., 400., 500.,\ 1000.,2000.,3000.,4000.,5000] _FillValue=999999 def __init__(self): wx.Frame.__init__(self, None, -1, self.title) self.create_menu() self.create_status_bar() self.create_main_panel() #self.draw_figure() def create_menu(self): self.menubar = wx.MenuBar() ### # File Menu ### menu_file = wx.Menu() # Load a hydro output file m_expt = menu_file.Append(-1, "&Open file\tCtrl-O", "Open netcdf file") self.Bind(wx.EVT_MENU, self.on_open_file, m_expt) # Load a grid file m_grid = menu_file.Append(-1, "&Load grid\tCtrl-G", "Load SUNTANS grid from folder") self.Bind(wx.EVT_MENU, self.on_load_grid, m_grid) # Load a particle file m_part = menu_file.Append(-1, "&Load PTM file\tCtrl-Shift-P", "Load a PTM file") self.Bind(wx.EVT_MENU, self.on_load_ptm, m_part) # Save current scene as an animation m_anim = menu_file.Append(-1,"&Save animation of current scene\tCtrl-S","Save animation") self.Bind(wx.EVT_MENU, self.on_save_anim, m_anim) # Save the current figure m_prin = menu_file.Append(-1,"&Print current scene\tCtrl-P","Save figure") self.Bind(wx.EVT_MENU, self.on_save_fig, m_prin) menu_file.AppendSeparator() # Exit m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) ### # Tools menu ### menu_tools = wx.Menu() m_gridstat = menu_tools.Append(-1, "&Plot grid size statistics", "SUNTANS grid size") self.Bind(wx.EVT_MENU, self.on_plot_gridstat, m_gridstat) m_countcells = menu_tools.Append(-1, "&Count # grid cells", "Grid cell count") self.Bind(wx.EVT_MENU, self.on_count_cells, m_countcells) m_overlaybathy = menu_tools.Append(-1, "&Overlay depth contours", "Depth overlay") self.Bind(wx.EVT_MENU, self.on_overlay_bathy, m_overlaybathy) ### # Help Menu ### menu_help = wx.Menu() m_about = menu_help.Append(-1, "&About\tF1", "About the demo") self.Bind(wx.EVT_MENU, self.on_about, m_about) # Add all of the menu bars self.menubar.Append(menu_file, "&File") self.menubar.Append(menu_tools, "&Tools") self.menubar.Append(menu_help, "&Help") self.SetMenuBar(self.menubar) def create_main_panel(self): """ Creates the main panel with all the controls on it: * mpl canvas * mpl navigation toolbar * Control panel for interaction """ self.panel = wx.Panel(self) # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.dpi = 100 #self.fig = Figure((7.0, 6.0), dpi=self.dpi,facecolor=self.bgcolor) self.fig = Figure((7.0, 6.0), dpi=self.dpi) self.canvas = FigCanvas(self.panel, -1, self.fig) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # self.axes = self.fig.add_subplot(111) #SetAxColor(self.axes,self.textcolor,self.bgcolor) # Bind the 'pick' event for clicking on one of the bars # #self.canvas.mpl_connect('pick_event', self.on_pick) ######## # Create widgets ######## self.variable_list = wx.ComboBox( self.panel, size=(200,-1), choices=['Select a variable...'], style=wx.CB_READONLY) self.variable_list.Bind(wx.EVT_COMBOBOX, self.on_select_variable) self.time_list = wx.ComboBox( self.panel, size=(200,-1), choices=['Select a time step...'], style=wx.CB_READONLY) self.time_list.Bind(wx.EVT_COMBOBOX, self.on_select_time) self.depthlayer_list = wx.ComboBox( self.panel, size=(200,-1), choices=['Select a vertical layer...'], style=wx.CB_READONLY) self.depthlayer_list.Bind(wx.EVT_COMBOBOX, self.on_select_depth) self.show_edge_check = wx.CheckBox(self.panel, -1, "Show Edges", style=wx.ALIGN_RIGHT) self.show_edge_check.Bind(wx.EVT_CHECKBOX, self.on_show_edges) if USECMOCEAN: cmaps=[] for cmap in cm.cmapnames: cmaps.append(cmap) cmaps.append(cmap+'_r') # Add all reverse map options else: # Use matplotlib standard cmaps = matplotlib.cm.datad.keys() cmaps.sort() self.colormap_list = wx.ComboBox( self.panel, size=(100,-1), choices=cmaps, style=wx.CB_READONLY) self.colormap_list.Bind(wx.EVT_COMBOBOX, self.on_select_cmap) self.colormap_label = wx.StaticText(self.panel, -1,"Colormap:") self.clim_check = wx.CheckBox(self.panel, -1, "Manual color limits ", style=wx.ALIGN_RIGHT) self.clim_check.Bind(wx.EVT_CHECKBOX, self.on_clim_check) self.climlow = wx.TextCtrl( self.panel, size=(100,-1), style=wx.TE_PROCESS_ENTER) self.climlow.Bind(wx.EVT_TEXT_ENTER, self.on_climlow) self.climhigh = wx.TextCtrl( self.panel, size=(100,-1), style=wx.TE_PROCESS_ENTER) self.climhigh.Bind(wx.EVT_TEXT_ENTER, self.on_climhigh) # Labels self.variable_label = wx.StaticText(self.panel, -1,"Variable:",size=(200,-1)) self.time_label = wx.StaticText(self.panel, -1,"Time step:",size=(200,-1)) self.depth_label = wx.StaticText(self.panel, -1,"Vertical level:",size=(200,-1)) # Create the navigation toolbar, tied to the canvas # self.toolbar = NavigationToolbar(self.canvas) #self.toolbar.toolitems[8][3]='my_save_fig' #def my_save_fig(self,*args): # print 'saving figure' # return "break" ######### # Layout with box sizers ######### self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.AddSpacer(10) #self.vbox.Add((-1,25)) flags = wx.ALIGN_LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL self.hbox0 = wx.BoxSizer(wx.HORIZONTAL) self.hbox0.Add(self.show_edge_check, 0, border=10, flag=flags) self.hbox0.Add(self.colormap_label, 0, border=10, flag=flags) self.hbox0.Add(self.colormap_list, 0, border=10, flag=flags) self.hbox0.Add(self.clim_check, 0, border=10, flag=flags) self.hbox0.Add(self.climlow, 0, border=10, flag=flags) self.hbox0.Add(self.climhigh, 0, border=10, flag=flags) self.vbox.AddSpacer(5) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.variable_label, 0, border=10, flag=flags) self.hbox1.Add(self.time_label, 0, border=10, flag=flags) self.hbox1.Add(self.depth_label, 0, border=10, flag=flags) self.vbox.AddSpacer(5) self.hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.hbox2.Add(self.variable_list, 0, border=10, flag=flags) self.hbox2.Add(self.time_list, 0, border=10, flag=flags) self.hbox2.Add(self.depthlayer_list, 0, border=10, flag=flags) self.vbox.Add(self.hbox1, 0, flag = wx.ALIGN_LEFT | wx.TOP) self.vbox.Add(self.hbox2, 0, flag = wx.ALIGN_LEFT | wx.TOP) self.vbox.Add(self.hbox0, 0, flag = wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) self.vbox.Fit(self) ########## # Event functions ########## def create_figure(self): """ Creates the figure """ # Find the colorbar limits if unspecified if self.autoclim: self.clim = [self.data.min(),self.data.max()] self.climlow.SetValue('%3.1f'%self.clim[0]) self.climhigh.SetValue('%3.1f'%self.clim[1]) if self.__dict__.has_key('collection'): #self.collection.remove() self.axes.collections.remove(self.collection) else: # First call - set the axes limits self.axes.set_aspect('equal') self.axes.set_xlim(self.xlims) self.axes.set_ylim(self.ylims) if self.collectiontype=='cells': self.collection = PolyCollection(self.xy,cmap=self.cmap) self.collection.set_array(np.array(self.data[:])) if not self.showedges: self.collection.set_edgecolors(self.collection.to_rgba(np.array((self.data[:])))) elif self.collectiontype=='edges': xylines = [self.xp[self.edges],self.yp[self.edges]] linesc = [zip(xylines[0][ii,:],xylines[1][ii,:]) for ii in range(self.Ne)] self.collection = LineCollection(linesc,array=np.array(self.data[:]),cmap=self.cmap) self.collection.set_clim(vmin=self.clim[0],vmax=self.clim[1]) self.axes.add_collection(self.collection) self.title=self.axes.set_title(self.genTitle(),color=self.textcolor) self.axes.set_xlabel('Easting [m]') self.axes.set_ylabel('Northing [m]') # create a colorbar if not self.__dict__.has_key('cbar'): self.cbar = self.fig.colorbar(self.collection) #SetAxColor(self.cbar.ax.axes,self.textcolor,self.bgcolor) else: #pass print 'Updating colorbar...' #self.cbar.check_update(self.collection) self.cbar.on_mappable_changed(self.collection) self.canvas.draw() def update_figure(self): if self.autoclim: self.clim = [self.data.min(),self.data.max()] self.climlow.SetValue('%3.1f'%self.clim[0]) self.climhigh.SetValue('%3.1f'%self.clim[1]) else: self.clim = [float(self.climlow.GetValue()),\ float(self.climhigh.GetValue())] # check whether it is cell or edge type if self.hasDim(self.variable,self.griddims['Ne']): self.collectiontype='edges' elif self.hasDim(self.variable,self.griddims['Nc']): self.collectiontype='cells' # Create a new figure if the variable has gone from cell to edge of vice # versa if not self.collectiontype==self.oldcollectiontype: self.create_figure() self.oldcollectiontype=self.collectiontype self.collection.set_array(np.array(self.data[:])) self.collection.set_clim(vmin=self.clim[0],vmax=self.clim[1]) # Cells only if self.collectiontype=='cells': if not self.showedges: self.collection.set_edgecolors(self.collection.to_rgba(np.array((self.data[:])))) else: self.collection.set_edgecolors('k') self.collection.set_linewidths(0.2) # Update the title self.title=self.axes.set_title(self.genTitle(),color=self.textcolor) #Update the colorbar self.cbar.update_normal(self.collection) # redraw the figure self.canvas.draw() def on_pick(self, event): # The event received here is of the type # matplotlib.backend_bases.PickEvent # # It carries lots of information, of which we're using # only a small amount here. # box_points = event.artist.get_bbox().get_points() msg = "You've clicked on a bar with coords:\n %s" % box_points dlg = wx.MessageDialog( self, msg, "Click!", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def on_select_variable(self, event): vname = event.GetString() self.flash_status_message("Selecting variable: %s"%vname) # update the spatial object and load the data self.variable = vname self.loadData(variable=self.variable) # Check if the variable has a depth coordinate depthstr = [''] # If so populate the vertical layer box if self.hasDim(self.variable,self.griddims['Nk']): depthstr = ['%3.1f'%self.z_r[k] for k in range(self.Nkmax)] depthstr += ['surface','seabed'] elif self.hasDim(self.variable,'Nkw'): depthstr = ['%3.1f'%self.z_w[k] for k in range(self.Nkmax+1)] self.depthlayer_list.SetItems(depthstr) # Update the plot self.update_figure() def on_select_time(self, event): self.tindex = event.GetSelection() # Update the object time index and reload the data if self.plot_type=='hydro': if not self.tstep==self.tindex: self.tstep=self.tindex self.loadData() self.flash_status_message("Selecting variable: %s..."%event.GetString()) # Update the plot self.update_figure() elif self.plot_type=='particles': self.PTM.plot(self.tindex,ax=self.axes,\ xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) self.canvas.draw() def on_select_depth(self, event): kindex = event.GetSelection() if not self.klayer[0]==kindex: # Check if its the seabed or surface value if kindex>=self.Nkmax: kindex=event.GetString() self.klayer = [kindex] self.loadData() self.flash_status_message("Selecting depth: %s..."%event.GetString()) # Update the plot self.update_figure() def on_open_file(self, event): file_choices = "SUNTANS NetCDF (*.nc)|*.nc*|UnTRIM NetCDF (*.nc)|*.nc*|All Files (*.*)|*.*" dlg = wx.FileDialog( self, message="Open SUNTANS file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style= wx.FD_MULTIPLE) if dlg.ShowModal() == wx.ID_OK: self.plot_type='hydro' path = dlg.GetPaths() # Initialise the class if dlg.GetFilterIndex() == 0 or dlg.GetFilterIndex() > 1: #SUNTANS self.flash_status_message("Opening SUNTANS file: %s" % path) try: Spatial.__init__(self, path, _FillValue=self._FillValue) except: Spatial.__init__(self, path, _FillValue=-999999) startvar='dv' if dlg.GetFilterIndex()==1: #UnTRIM self.flash_status_message("Opening UnTRIMS file: %s" % path) #Spatial.__init__(self,path,gridvars=untrim_gridvars,griddims=untrim_griddims) UNTRIMSpatial.__init__(self,path) startvar='Mesh2_face_depth' # Populate the drop down menus vnames = self.listCoordVars() self.variable_list.SetItems(vnames) # Update the time drop down list if self.__dict__.has_key('time'): self.timestr = [datetime.strftime(tt,'%d-%b-%Y %H:%M:%S') for tt in self.time] else: # Assume that it is a harmonic-type file self.timestr = self.nc.Constituent_Names.split() self.time_list.SetItems(self.timestr) # Draw the depth if startvar in vnames: self.variable=startvar self.loadData() self.create_figure() def on_load_grid(self, event): dlg = wx.DirDialog( self, message="Open SUNTANS grid from folder...", defaultPath=os.getcwd(), style= wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() # Initialise the class self.flash_status_message("Opening SUNTANS grid from folder: %s" % path) Grid.__init__(self,path) # Plot the Grid if self.__dict__.has_key('collection'): self.axes.collections.remove(self.collection) self.axes,self.collection = self.plotmesh(ax=self.axes,edgecolors='y') # redraw the figure self.canvas.draw() def on_load_ptm(self, event): file_choices = "PTM NetCDF (*.nc)|*.nc|PTM Binary (*_bin.out)|*_bin.out|All Files (*.*)|*.*" dlg = wx.FileDialog( self, message="Open PTM file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style= wx.FD_MULTIPLE) if dlg.ShowModal() == wx.ID_OK: self.plot_type = 'particles' path = dlg.GetPath() # Initialise the class if dlg.GetFilterIndex() == 0: #SUNTANS self.flash_status_message("Opening PTM netcdf file: %s" % path) self.PTM = PtmNC(path) elif dlg.GetFilterIndex() == 1: #PTM self.flash_status_message("Opening PTM binary file: %s" % path) self.PTM = PtmBin(path) self.Nt = self.PTM.nt # Update the time drop down list self.timestr = [datetime.strftime(tt,'%d-%b-%Y %H:%M:%S') for tt in self.PTM.time] self.time_list.SetItems(self.timestr) # Plot the first time step if self.__dict__.has_key('xlims'): self.PTM.plot(self.PTM.nt-1,ax=self.axes,xlims=self.xlims,\ ylims=self.ylims,color=self.particlecolor,\ fontcolor='w',markersize=self.particlesize) else: self.PTM.plot(self.PTM.nt-1,ax=self.axes,fontcolor='w',\ color=self.particlecolor,markersize=self.particlesize) # redraw the figure self.canvas.draw() def on_show_edges(self,event): sender=event.GetEventObject() self.showedges = sender.GetValue() # Update the figure self.update_figure() def on_clim_check(self,event): sender=event.GetEventObject() if sender.GetValue() == True: self.autoclim=False self.update_figure() else: self.autoclim=True def on_climlow(self,event): self.clim[0] = event.GetString() #self.update_figure() def on_climhigh(self,event): self.clim[1] = event.GetString() #self.update_figure() def on_select_cmap(self,event): self.cmap=event.GetString() if USECMOCEAN: self.collection.set_cmap(getattr(cm,self.cmap)) else: self.collection.set_cmap(self.cmap) # Update the figure self.update_figure() def on_save_fig(self,event): """ Save a figure of the current scene to a file """ file_choices = " (*.png)|*.png| (*.pdf)|*.pdf |(*.jpg)|*.jpg |(*.eps)|*eps " filters=['.png','.pdf','.png','.png'] dlg = wx.FileDialog( self, message="Save figure to file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style= wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() ext = filters[dlg.GetFilterIndex()] if ext in path: outfile=path else: outfile = path+ext self.fig.savefig(outfile) def on_save_anim(self,event): """ Save an animation of the current scene to a file """ file_choices = "Quicktime (*.mov)|*.mov| (*.gif)|*.gif| (*.avi)|*.avi |(*.mp4)|*.mp4 " filters=['.mov','.gif','.avi','.mp4'] dlg = wx.FileDialog( self, message="Output animation file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style= wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() ext = filters[dlg.GetFilterIndex()] if ext in path: outfile=path else: outfile = path+ext self.flash_status_message("Saving figure to file: %s" %outfile) self.flash_status_message("Saving animation to file: %s" %outfile) # Create the animation #self.tstep = range(self.Nt) # Use all time steps for animation #self.animate(cbar=self.cbar,cmap=self.cmap,\ # xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) def initanim(): if not self.plot_type=='particles': return (self.title, self.collection) else: return (self.PTM.title,self.PTM.p_handle) def updateScalar(i): if not self.plot_type=='particles': self.tstep=[i] self.loadData() self.update_figure() return (self.title,self.collection) elif self.plot_type=='particles': self.PTM.plot(i,ax=self.axes,\ xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) return (self.PTM.title,self.PTM.p_handle) self.anim = animation.FuncAnimation(self.fig, \ updateScalar, init_func = initanim, frames=self.Nt, interval=50, blit=True) if ext=='.gif': self.anim.save(outfile,writer='imagemagick',fps=6) elif ext=='.mp4': print 'Saving html5 video...' # Ensures html5 compatibility self.anim.save(outfile,writer='mencoder',fps=6,\ bitrate=3600,extra_args=['-ovc','x264']) # mencoder options #bitrate=3600,extra_args=['-vcodec','libx264']) else: self.anim.save(outfile,writer='mencoder',fps=6,bitrate=3600) # Return the figure back to its status del self.anim self.tstep=self.tindex if not self.plot_type=='particles': self.loadData() self.update_figure() # Bring up a dialog box dlg2= wx.MessageDialog(self, 'Animation complete.', "Done", wx.OK) dlg2.ShowModal() dlg2.Destroy() def on_exit(self, event): self.Destroy() def on_about(self, event): msg = """ SUNTANS NetCDF visualization tool *Author: Matt Rayson *Institution: Stanford University *Created: October 2013 """ dlg = wx.MessageDialog(self, msg, "About", wx.OK) dlg.ShowModal() dlg.Destroy() def on_count_cells(self,eveny): msg = "Total 3-D grid cells = %d"%(self.count_cells()) dlg = wx.MessageDialog(self, msg, "No. cells", wx.OK) dlg.ShowModal() dlg.Destroy() def on_overlay_bathy(self,event): # Plot depth contours print 'Plotting contours...' self.contourf(z=self.dv, clevs=self.depthlevs,\ ax=self.axes,\ filled=False, colors='0.5', linewidths=0.5, zorder=1e6) print 'Done' def on_plot_gridstat(self, event): """ Plot the grid size histogram in a new figure """ matplotlib.pyplot.figure() self.plothist() matplotlib.pyplot.show() def create_status_bar(self): self.statusbar = self.CreateStatusBar() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('')
shp = ShapeFile('.../states/statessp020') dbf = dbflib.open('../states/statessp020') for npoly in range(shp.info()[0]): # 在地图上绘制彩色多边形 shpsegs = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for rings in range(rings): lons, lats = zip(*verts[ring]) x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring == 0: shapedict = dbf.read_record(npoly) name = shapedict['STATE'] lines = LineCollection(shpsegs, antialiaseds=(1, )) # state_to_code字典,例如'ALASKA' -> 'AK', omitted try: per = obama[state_to_code[name.upper()]] except KeyError: continue lines.set_facecolors('k') lines.set_alpha(0.75 * per) lines.set_edgecolors('k') lines.set_linewidth(0.3) plt.show()
dbf = dbflib.open('../states/statesp020') for npoly in range(shp.info()[0]): # draw colored polygons on the map shpseqs = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) x, y = m(lons,lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) name = shapedict['STATE'] lines = LineCollection(shpsegs,antialiased=(1,)) # state_to_code dict, e.g. 'ALASKA' -> 'AK', omitted try: per = obama[state_to_code[name.upper()]] except KeyError: continue lines.set_facecolors('k') lines.set_alpha(0.75 * per) # shrink the percentage a bit lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) plt.show()
def generate_map(countries): # Initialize plotting area, set the boundaries and add a sub-plot on which # we are going to plot the map fig = plt.figure(figsize=(11.7, 8.3)) plt.subplots_adjust(left=0.05, right=0.95, top=0.90, bottom=0.05, wspace=0.15, hspace=0.05) ax = plt.subplot(111) # Initialize the basemap, set the resolution, projection type and the viewport bm = Basemap(resolution='i', projection='robin', lon_0=0) # Tell basemap how to draw the countries (built-in shapes), draw parallels and meridians # and color in the water bm.drawcountries(linewidth=0.5) bm.drawparallels(np.arange(-90., 120., 30.)) bm.drawmeridians(np.arange(0., 360., 60.)) bm.drawmapboundary(fill_color='aqua') # Open the countries shapefile and read the shape and attribute information r = shapefile.Reader('world_borders/TM_WORLD_BORDERS-0.3.shp') shapes = r.shapes() records = r.records() # Iterate through all records (attributes) and shapes (countries) for record, shape in zip(records, shapes): # Extract longitude and latitude values into two separate arrays then # project the coordinates onto the map projection and transpose the array, so that # the data variable contains (lon, lat) pairs in the list. # Basically, the following two lines convert the initial data # [ [lon_original_1, lat_original_1], [lon_original_2, lat_original_2], ... ] # into projected data # [ [lon_projected_1, lat_projected_1, [lon_projected_2, lat_projected_2], ... ] # # Note: Calling baseshape object with the coordinates as an argument returns the # projection of those coordinates lon_array, lat_array = zip(*shape.points) data = np.array(bm(lon_array, lat_array)).T # Next we will create groups of points by splitting the shape.points according to # the indices provided in shape.parts if len(shape.parts) == 1: # If the shape has only one part, then we have only one group. Easy. groups = [ data, ] else: # If we have more than one part ... groups = [] for i in range(1, len(shape.parts)): # We iterate through all parts, and find their start and end positions index_start = shape.parts[i - 1] index_end = shape.parts[i] # Then we copy all point between two indices into their own group and append # that group to the list groups.append(data[index_start:index_end]) # Last group starts at the last index and finishes at the end of the points list groups.append(data[index_end:]) # Create a collection of lines provided the group of points. Each group represents a line. lines = LineCollection(groups, antialiaseds=(1, )) # We then select a color from a color map (in this instance all Reds) # The intensity of the selected color is proportional to the number of requests. # Color map accepts values from 0 to 1, therefore we need to normalize our request count # figures, so that the max number of requests is 1, and the rest is proportionally spread # in the range from 0 to 1. max_value = float(max(countries.values())) country_name = record[4] requests = countries.get(country_name, 0) requests_norm = requests / max_value lines.set_facecolors(cm.Reds(requests_norm)) # Finally we set the border color to be black and add the shape to the sub-plot lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) # Once we are ready, we save the resulting picture plt.savefig('requests_per_country.png', dpi=300)
index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) lines = LineCollection(segs,antialiaseds=(1,)) #Now obtain the data in a given poly and assign a color to the value div = str(record[5]) dval = divlookup(dfile,div,yyyy,int(mm)) if(len(div) < 4): div = '0'+div nval = normlookup(normfile, div, int(mm)) dval = dval-nval #Now normalize the data and map it to the color ramp dval = (dval - valmin) * (255/(valmax-valmin)) #if(dval > valmax): dval = valmax - 0.1 lines.set_facecolors(cmap(int(dval))) lines.set_edgecolors(cmap(int(dval))) lines.set_linewidth(0.25) ax1.add_collection(lines) if(imgsize == 'GEO'): inProj = Proj(init='epsg:3338') outProj = Proj(init='epsg:4326') #Now read in the Alaska Climate Division Shapes and fill the basemap s = shapefile.Reader(r"./Shapefiles/AK_divisions_NAD83") shapes = s.shapes() records = s.records() for record, shape in zip(records,shapes): lons,lats = zip(*shape.points) lons,lats = transform(inProj,outProj,lons,lats)
def map_communities_and_commutes(G): G_mod = nx.read_gml("/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/total_commuting_G_scaled_weights_11COM_713_7115.gml") col = [str]*256 for i in range(256): col[i] = 'w' for node in G_mod.nodes_iter(data=True): #print node[1]['label'] col_gephi = node[1]['graphics']['fill'] while (len(col_gephi) < 7): col_gephi += '0' subpref_gephi = int(float(node[1]['label'])) print subpref_gephi, col_gephi col[subpref_gephi] = col_gephi #print col plt.clf() plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) # read the shapefile archive s = m.readshapefile('/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE', 'subpref') from shapelib import ShapeFile import dbflib from matplotlib.collections import LineCollection from matplotlib import cm shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) x, y = m(lons, lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs,antialiaseds=(1,)) lines.set_facecolors(col[subpref_id]) lines.set_edgecolors('gray') lines.set_linewidth(0.3) ax.add_collection(lines) m.drawcoastlines() plt.show() # # data to plot on the map # lons = [int]*256 # lats = [int]*256 # # # read in coordinates fo subprefs # file_name2 = "/home/sscepano/DATA SET7S/D4D/SUBPREF_POS_LONLAT.TSV" # f2 = open(file_name2, 'r') # # # read subpref coordinates # subpref_coord = {} # for line in f2: # subpref_id, lon, lat = line.split('\t') # lon = float(lon) # lat = float(lat) # subpref_id = int(subpref_id) # subpref_coord.keys().append(subpref_id) # subpref_coord[subpref_id] = (lon, lat) # # f2.close() # # # if wanna plot number of users whose this is home subpref # for subpref in range(1,256): # lons[subpref] = subpref_coord[subpref][0] # lats[subpref] = subpref_coord[subpref][1] # # # if G.has_node(-1): # G.remove_node(-1) # # max7s = 1 # min7s = 1 # for u,v,d in G.edges(data=True): # if d['weight'] > max7s: # max7s = d['weight'] # if d['weight'] < min7s: # min7s = d['weight'] # # max7s = float(max7s) # print max7s # print min7s # # scaled_weight = defaultdict(int) # for i in range(256): # scaled_weight[i] = defaultdict(int) # # for u,v,d in G.edges(data=True): # node1 = G.nodes(data=True)[u][1]['label'] # node2 = G.nodes(data=True)[v][1]['label'] # print u, node1 # print v, node2 # print d # scaled_weight[node1][node2] = (d['weight'] - min7s) / (max7s - min7s) # ## for u,v,d in G.edges(data=True): ## print u,v,d ## node1 = G.nodes(data=True)[u][1]['label'] ## node2 = G.nodes(data=True)[v][1]['label'] ## print node1, G_mod.nodes(data=True)[u][1]['label'] ## print node2, G_mod.nodes(data=True)[v][1]['label'] # # # for u, v, d in G.edges(data=True): # node1 = G.nodes(data=True)[u][1]['label'] # node2 = G.nodes(data=True)[v][1]['label'] # print node1 # print node2 # lo = [] # la = [] # print u # print v # lo.append(lons[node1]) # lo.append(lons[node2]) # la.append(lats[node1]) # la.append(lats[node2]) # #m.drawgreatcircle(lons[u],lats[u], lons[v],lats[v]) # x, y = m(lo, la) # #linewidth7s = d['weight'] # #linewidth7s = d['weight'] / max7s # #lons, lats = n.meshgrid(lo,la) # linewidth7s = scaled_weight[node1][node2] * 7 + 0.2 # m.plot(x,y, 'b', linewidth = linewidth7s) # #wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons)) # #mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.) # #m.contour(x,y,linewidth=linewidth7s) # #m.quiver(x,y,lons, lats, latlon=True) ## if linewidth7s > 1: ## print linewidth7s # # # figure_name = "/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/maps/mod_classes_SCALED_11COM_713_7115.png" # print(figure_name) # plt.savefig(figure_name, format = "png",dpi=1000) return
rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring == 0: shapedict = dbf.read_record(npoly) print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] num = ["%.2f" % traj[subpref_id]] # for name, xc, yc in zip(num, x, y): # plt.text(xc, yc, name) # color_col # add information about ring number to dictionary. shapedict["RINGNUM"] = ring + 1 shapedict["SHAPENUM"] = npoly + 1 shpinfo.append(shapedict) # print subpref_id # print name lines = LineCollection(shpsegs, antialiaseds=(1,)) lines.set_facecolors(str(1 - traj[subpref_id])) lines.set_edgecolors("k") lines.set_linewidth(0.3) ax.add_collection(lines) plt.savefig("/home/sscepano/D4D res/allstuff/CLUSTERING/subpref res/maps/grayscale_pct_night_c_map2.png", dpi=1000) # plt.show()
class DecayLine(object): def __init__(self, n_points, tail_length, rgb_color, zorder=2, label=None): self.n_points = int(n_points) self.tail_length = int(tail_length) self.rgb_color = rgb_color self._zorder = zorder self.lc = None self._label = label self.dbg = True def __str__(self): if not hasattr(self, 'points') or not hasattr(self, 'segments'): return "" res = "DecayLine:" + "\n\t{}".format(self.segments) return res def set_data(self, x=None, y=None): if x is None or y is None: self.lc = LineCollection([], linewidths=1.0, zorder=self._zorder) else: # ensure we don't start with more points than we want x = x[-self.n_points:] y = y[-self.n_points:] # create a list of points with shape (len(x), 1, 2) # array([[[ x0 , y0 ]], # [[ x1 , y1 ]], # ..., # [[ xn , yn ]]]) #self.points = np.array([x, y]).T.reshape(-1, 1, 2) if not hasattr(self, 'points'): self.points = deque([[x[i], y[i]] for i in range(len(x))]) else: for i in range(len(x)): self.points.append([x[i], y[i]]) # group each point with the one following it (shape (len(x)-1, 2, 2)): # array([[[ x0 , y0 ], # [ x1 , y1 ]], # [[ x1 , y1 ], # [ x2 , y2 ]], # ... # self.segments = np.concatenate([self.points[:-1], self.points[1:]], axis=1) if len(self.points) > 1: pts = np.array(self.points).reshape(-1, 1, 2) self.segments = np.concatenate([pts[:-1], pts[1:]], axis=1) if hasattr(self, 'alphas'): del self.alphas if hasattr(self, 'rgba_colors'): del self.rgba_colors if self.lc is None: self.lc = LineCollection( self.segments, colors=self.get_colors(), linewidths=1.0, zorder=self._zorder, label="" if self._label is None else self._label) self.lc.set_segments(self.segments) colours = self.get_colors() if self.dbg: print(colours) self.dbg = False self.lc.set_color(colours) self.lc.set_edgecolors(colours) # self.lc.set_facecolors(colours) else: if self.lc is None: self.lc = LineCollection( [], linewidths=1.0, colors=(self.rgb_color[0], self.rgb_color[1], self.rgb_color[2], 1.0), zorder=self._zorder, label="" if self._label is None else self._label) def get_LineCollection(self): if not hasattr(self, 'lc'): self.set_data() return self.lc def get_label(self): """Return the label used for this artist in the legend.""" if self.lc is None: return "" if self._label is None else self._label return self.lc.get_label() def set_label(self, s): self._label = s if self.lc is not None: self.lc.set_label(self._label) def add_point(self, x, y): if not hasattr(self, 'points') or not hasattr(self, 'segments'): self.set_data([x], [y]) else: # TODO: could use a circular buffer to reduce memory operations... # self.segments = np.concatenate((self.segments,[[self.points[-1][0],[x,y]]])) # self.points = np.concatenate((self.points, [[[x,y]]])) self.points.append([x, y]) # remove points if necessary: while len(self.points) > self.n_points: self.points.popleft() pts = np.array(self.points).reshape(-1, 1, 2) self.segments = np.concatenate([pts[:-1], pts[1:]], axis=1) self.lc.set_segments(self.segments) colours = self.get_colors() self.lc.set_color(colours) self.lc.set_edgecolors(colours) # self.lc.set_facecolors(colours) @property def npoints(self): if not hasattr(self, 'points'): return 0 else: #return self.points.shape[0] return len(self.points) def get_alphas(self): n_segments = self.n_points - 1 n = len(self.segments) # n = self.points.shape[0] if n < n_segments: rest_length = n_segments - self.tail_length if n <= rest_length: return np.ones(n) else: tail_length = n - rest_length tail = np.linspace(1. / tail_length, 1., tail_length) rest = np.ones(rest_length) return np.concatenate((tail, rest), axis=None) else: # n == n_segments if not hasattr(self, 'alphas'): tail = np.linspace(1. / self.tail_length, 1., self.tail_length) rest = np.ones(n_segments - self.tail_length) self.alphas = np.concatenate((tail, rest), axis=None) return self.alphas def get_colors(self): n_segments = self.n_points - 1 n = len(self.segments) if n < 2: # return [self.rgb_color+[1.] for i in range(n)] colour = None if isinstance(self.rgb_color, np.ndarray): colour = np.concatenate([self.rgb_color, [ 1.0, ]]) elif type(self.rgb_color) in [list, tuple]: colour = self.rgb_color + [1.] return [colour for i in range(n)] if n < n_segments: alphas = self.get_alphas() rgba_colors = np.zeros((n, 4), dtype=np.float32) # first place the rgb color in the first three columns rgba_colors[:, 0:3] = self.rgb_color[:] # and the fourth column needs to be your alphas rgba_colors[:, 3] = alphas # self.rgba_colors = rgba_colors # return self.rgba_colors return rgba_colors else: if hasattr(self, 'rgba_colors'): pass else: alphas = self.get_alphas() rgba_colors = np.zeros((n, 4), dtype=np.float32) # first place the rgb color in the first three columns rgba_colors[:, 0:3] = self.rgb_color[:] # and the fourth column needs to be your alphas rgba_colors[:, 3] = alphas self.rgba_colors = rgba_colors return self.rgba_colors get_color = get_colors # for compatibility with old versions
def country(countries, bmap, fc=None, ec='none', lw=1, alpha=1, adm=0, gadmpath='/home/dtr/Documents/Webpages/blog-notebooks/data/TravelMap/'): """Colour <countries> with a <bmap> projection. This script is adapted from: http://www.geophysique.be/2013/02/12/ matplotlib-basemap-tutorial-10-shapefiles-unleached-continued I downloaded the countries shapefile from the *Global Administrative Areas* website, [gadm.org](http://gadm.org). => You have to use the same abbreviations for the countries as GADM does, or adjust the script. => You have to download the shapefiles from GADM, and extract them into the <gadmpath> directory. Of course, you can use any other shapfiles you have, and adjust the script accordingly. Parameters ---------- countries : string or list of strings Countries to be plotted. bmap : handle As you get from bmap = Basemap(). fc : None or colour, or list of colours; <None> Face-colour for country; if <None>, it will cycle through colour-cycle. ec : 'none' or colour (scalar or list); <'none'> Edge-colour for country. lw : scalar or list; <1> Linewidth for country. alpha: scalar or list; <1> Transparency. adm : {0, 1, 2, 3}; <0> Administrative area to choose. gadmpath : 'string' Absolut or relative path to shapefiles. """ # Ensure countries is a list if not isinstance(countries, list): countries = [countries,] # Get current axis cax = plt.gca() # Loop through the countries for country in countries: # Get shapefile for the country; extract shapes and records r = shapefile.Reader(gadmpath+country+'_adm/'+country+'_adm'+str(adm)) shapes = r.shapes() records = r.records() # Loop through the records; for adm0 this is only 1 run n = 0 for record, shape in zip(records,shapes): lons,lats = zip(*shape.points) data = np.array(bmap(lons, lats)).T if len(shape.parts) == 1: segs = [data,] else: 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,)) # If facecolor is provided, use; else cycle through colours if fc: if not isinstance(fc, list): lines.set_facecolors(fc) else: lines.set_facecolors(fc[n]) else: cycle = cax._get_lines.prop_cycler lines.set_facecolors(next(cycle)['color']) # Edge colour if not isinstance(ec, list): lines.set_edgecolors(ec) else: lines.set_edgecolors(ec[n]) # Alpha if not isinstance(alpha, list): lines.set_alpha(alpha) else: lines.set_alpha(alpha[n]) # Line width if not isinstance(lw, list): lines.set_linewidth(lw) else: lines.set_linewidth(lw[n]) # Add to current plot cax.add_collection(lines) n += 1
class SunPlotPy(wx.Frame, Spatial, Grid): """ The main frame of the application """ title = 'sunplot(py)' # Plotting options autoclim = True showedges = False bgcolor = 'k' textcolor = 'w' cmap = 'RdBu' particlesize = 1.8 particlecolor = 'm' # other flags collectiontype = 'cells' oldcollectiontype = 'cells' # tindex = 0 depthlevs = [0., 10., 100., 200., 300., 400., 500.,\ 1000.,2000.,3000.,4000.,5000] _FillValue = 999999 def __init__(self): wx.Frame.__init__(self, None, -1, self.title) self.create_menu() self.create_status_bar() self.create_main_panel() #self.draw_figure() def create_menu(self): self.menubar = wx.MenuBar() ### # File Menu ### menu_file = wx.Menu() # Load a hydro output file m_expt = menu_file.Append(-1, "&Open file\tCtrl-O", "Open netcdf file") self.Bind(wx.EVT_MENU, self.on_open_file, m_expt) # Load a grid file m_grid = menu_file.Append(-1, "&Load grid\tCtrl-G", "Load SUNTANS grid from folder") self.Bind(wx.EVT_MENU, self.on_load_grid, m_grid) # Load a particle file m_part = menu_file.Append(-1, "&Load PTM file\tCtrl-Shift-P", "Load a PTM file") self.Bind(wx.EVT_MENU, self.on_load_ptm, m_part) # Save current scene as an animation m_anim = menu_file.Append(-1, "&Save animation of current scene\tCtrl-S", "Save animation") self.Bind(wx.EVT_MENU, self.on_save_anim, m_anim) # Save the current figure m_prin = menu_file.Append(-1, "&Print current scene\tCtrl-P", "Save figure") self.Bind(wx.EVT_MENU, self.on_save_fig, m_prin) menu_file.AppendSeparator() # Exit m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) ### # Tools menu ### menu_tools = wx.Menu() m_gridstat = menu_tools.Append(-1, "&Plot grid size statistics", "SUNTANS grid size") self.Bind(wx.EVT_MENU, self.on_plot_gridstat, m_gridstat) m_countcells = menu_tools.Append(-1, "&Count # grid cells", "Grid cell count") self.Bind(wx.EVT_MENU, self.on_count_cells, m_countcells) m_overlaybathy = menu_tools.Append(-1, "&Overlay depth contours", "Depth overlay") self.Bind(wx.EVT_MENU, self.on_overlay_bathy, m_overlaybathy) ### # Help Menu ### menu_help = wx.Menu() m_about = menu_help.Append(-1, "&About\tF1", "About the demo") self.Bind(wx.EVT_MENU, self.on_about, m_about) # Add all of the menu bars self.menubar.Append(menu_file, "&File") self.menubar.Append(menu_tools, "&Tools") self.menubar.Append(menu_help, "&Help") self.SetMenuBar(self.menubar) def create_main_panel(self): """ Creates the main panel with all the controls on it: * mpl canvas * mpl navigation toolbar * Control panel for interaction """ self.panel = wx.Panel(self) # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.dpi = 100 #self.fig = Figure((7.0, 6.0), dpi=self.dpi,facecolor=self.bgcolor) self.fig = Figure((7.0, 6.0), dpi=self.dpi) self.canvas = FigCanvas(self.panel, -1, self.fig) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # self.axes = self.fig.add_subplot(111) #SetAxColor(self.axes,self.textcolor,self.bgcolor) # Bind the 'pick' event for clicking on one of the bars # #self.canvas.mpl_connect('pick_event', self.on_pick) ######## # Create widgets ######## self.variable_list = wx.ComboBox(self.panel, size=(200, -1), choices=['Select a variable...'], style=wx.CB_READONLY) self.variable_list.Bind(wx.EVT_COMBOBOX, self.on_select_variable) self.time_list = wx.ComboBox(self.panel, size=(200, -1), choices=['Select a time step...'], style=wx.CB_READONLY) self.time_list.Bind(wx.EVT_COMBOBOX, self.on_select_time) self.depthlayer_list = wx.ComboBox( self.panel, size=(200, -1), choices=['Select a vertical layer...'], style=wx.CB_READONLY) self.depthlayer_list.Bind(wx.EVT_COMBOBOX, self.on_select_depth) self.show_edge_check = wx.CheckBox(self.panel, -1, "Show Edges", style=wx.ALIGN_RIGHT) self.show_edge_check.Bind(wx.EVT_CHECKBOX, self.on_show_edges) if USECMOCEAN: cmaps = [] for cmap in cm.cmapnames: cmaps.append(cmap) cmaps.append(cmap + '_r') # Add all reverse map options else: # Use matplotlib standard cmaps = list(matplotlib.cm.datad.keys()) cmaps.sort() self.colormap_list = wx.ComboBox(self.panel, size=(100, -1), choices=cmaps, style=wx.CB_READONLY) self.colormap_list.Bind(wx.EVT_COMBOBOX, self.on_select_cmap) self.colormap_label = wx.StaticText(self.panel, -1, "Colormap:") self.clim_check = wx.CheckBox(self.panel, -1, "Manual color limits ", style=wx.ALIGN_RIGHT) self.clim_check.Bind(wx.EVT_CHECKBOX, self.on_clim_check) self.climlow = wx.TextCtrl(self.panel, size=(100, -1), style=wx.TE_PROCESS_ENTER) self.climlow.Bind(wx.EVT_TEXT_ENTER, self.on_climlow) self.climhigh = wx.TextCtrl(self.panel, size=(100, -1), style=wx.TE_PROCESS_ENTER) self.climhigh.Bind(wx.EVT_TEXT_ENTER, self.on_climhigh) # Labels self.variable_label = wx.StaticText(self.panel, -1, "Variable:", size=(200, -1)) self.time_label = wx.StaticText(self.panel, -1, "Time step:", size=(200, -1)) self.depth_label = wx.StaticText(self.panel, -1, "Vertical level:", size=(200, -1)) # Create the navigation toolbar, tied to the canvas # self.toolbar = NavigationToolbar(self.canvas) #self.toolbar.toolitems[8][3]='my_save_fig' #def my_save_fig(self,*args): # print 'saving figure' # return "break" ######### # Layout with box sizers ######### self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.AddSpacer(10) #self.vbox.Add((-1,25)) flags = wx.ALIGN_LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL self.hbox0 = wx.BoxSizer(wx.HORIZONTAL) self.hbox0.Add(self.show_edge_check, 0, border=10, flag=flags) self.hbox0.Add(self.colormap_label, 0, border=10, flag=flags) self.hbox0.Add(self.colormap_list, 0, border=10, flag=flags) self.hbox0.Add(self.clim_check, 0, border=10, flag=flags) self.hbox0.Add(self.climlow, 0, border=10, flag=flags) self.hbox0.Add(self.climhigh, 0, border=10, flag=flags) self.vbox.AddSpacer(5) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.variable_label, 0, border=10, flag=flags) self.hbox1.Add(self.time_label, 0, border=10, flag=flags) self.hbox1.Add(self.depth_label, 0, border=10, flag=flags) self.vbox.AddSpacer(5) self.hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.hbox2.Add(self.variable_list, 0, border=10, flag=flags) self.hbox2.Add(self.time_list, 0, border=10, flag=flags) self.hbox2.Add(self.depthlayer_list, 0, border=10, flag=flags) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.vbox.Add(self.hbox2, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.vbox.Add(self.hbox0, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) self.vbox.Fit(self) ########## # Event functions ########## def create_figure(self): """ Creates the figure """ # Find the colorbar limits if unspecified if self.autoclim: self.clim = [self.data.min(), self.data.max()] self.climlow.SetValue('%3.1f' % self.clim[0]) self.climhigh.SetValue('%3.1f' % self.clim[1]) if 'collection' in self.__dict__: #self.collection.remove() self.axes.collections.remove(self.collection) else: # First call - set the axes limits self.axes.set_aspect('equal') self.axes.set_xlim(self.xlims) self.axes.set_ylim(self.ylims) if self.collectiontype == 'cells': self.collection = PolyCollection(self.xy, cmap=self.cmap) self.collection.set_array(np.array(self.data[:])) if not self.showedges: self.collection.set_edgecolors( self.collection.to_rgba(np.array((self.data[:])))) elif self.collectiontype == 'edges': xylines = [self.xp[self.edges], self.yp[self.edges]] linesc = [ list(zip(xylines[0][ii, :], xylines[1][ii, :])) for ii in range(self.Ne) ] self.collection = LineCollection(linesc, array=np.array(self.data[:]), cmap=self.cmap) self.collection.set_clim(vmin=self.clim[0], vmax=self.clim[1]) self.axes.add_collection(self.collection) self.title = self.axes.set_title(self.genTitle(), color=self.textcolor) self.axes.set_xlabel('Easting [m]') self.axes.set_ylabel('Northing [m]') # create a colorbar if 'cbar' not in self.__dict__: self.cbar = self.fig.colorbar(self.collection) #SetAxColor(self.cbar.ax.axes,self.textcolor,self.bgcolor) else: #pass print('Updating colorbar...') #self.cbar.check_update(self.collection) self.cbar.on_mappable_changed(self.collection) self.canvas.draw() def update_figure(self): if self.autoclim: self.clim = [self.data.min(), self.data.max()] self.climlow.SetValue('%3.1f' % self.clim[0]) self.climhigh.SetValue('%3.1f' % self.clim[1]) else: self.clim = [float(self.climlow.GetValue()),\ float(self.climhigh.GetValue())] # check whether it is cell or edge type if self.hasDim(self.variable, self.griddims['Ne']): self.collectiontype = 'edges' elif self.hasDim(self.variable, self.griddims['Nc']): self.collectiontype = 'cells' # Create a new figure if the variable has gone from cell to edge of vice # versa if not self.collectiontype == self.oldcollectiontype: self.create_figure() self.oldcollectiontype = self.collectiontype self.collection.set_array(np.array(self.data[:])) self.collection.set_clim(vmin=self.clim[0], vmax=self.clim[1]) # Cells only if self.collectiontype == 'cells': if not self.showedges: self.collection.set_edgecolors( self.collection.to_rgba(np.array((self.data[:])))) else: self.collection.set_edgecolors('k') self.collection.set_linewidths(0.2) # Update the title self.title = self.axes.set_title(self.genTitle(), color=self.textcolor) #Update the colorbar self.cbar.update_normal(self.collection) # redraw the figure self.canvas.draw() def on_pick(self, event): # The event received here is of the type # matplotlib.backend_bases.PickEvent # # It carries lots of information, of which we're using # only a small amount here. # box_points = event.artist.get_bbox().get_points() msg = "You've clicked on a bar with coords:\n %s" % box_points dlg = wx.MessageDialog(self, msg, "Click!", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def on_select_variable(self, event): vname = event.GetString() self.flash_status_message("Selecting variable: %s" % vname) # update the spatial object and load the data self.variable = vname self.loadData(variable=self.variable) # Check if the variable has a depth coordinate depthstr = [''] # If so populate the vertical layer box if self.hasDim(self.variable, self.griddims['Nk']): depthstr = ['%3.1f' % self.z_r[k] for k in range(self.Nkmax)] depthstr += ['surface', 'seabed'] elif self.hasDim(self.variable, 'Nkw'): depthstr = ['%3.1f' % self.z_w[k] for k in range(self.Nkmax + 1)] self.depthlayer_list.SetItems(depthstr) # Update the plot self.update_figure() def on_select_time(self, event): self.tindex = event.GetSelection() # Update the object time index and reload the data if self.plot_type == 'hydro': if not self.tstep == self.tindex: self.tstep = self.tindex self.loadData() self.flash_status_message("Selecting variable: %s..." % event.GetString()) # Update the plot self.update_figure() elif self.plot_type == 'particles': self.PTM.plot(self.tindex,ax=self.axes,\ xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) self.canvas.draw() def on_select_depth(self, event): kindex = event.GetSelection() if not self.klayer[0] == kindex: # Check if its the seabed or surface value if kindex >= self.Nkmax: kindex = event.GetString() self.klayer = [kindex] self.loadData() self.flash_status_message("Selecting depth: %s..." % event.GetString()) # Update the plot self.update_figure() def on_open_file(self, event): file_choices = "SUNTANS NetCDF (*.nc)|*.nc*|UnTRIM NetCDF (*.nc)|*.nc*|All Files (*.*)|*.*" dlg = wx.FileDialog(self, message="Open SUNTANS file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style=wx.FD_MULTIPLE) if dlg.ShowModal() == wx.ID_OK: self.plot_type = 'hydro' path = dlg.GetPaths() # Initialise the class if dlg.GetFilterIndex() == 0 or dlg.GetFilterIndex() > 1: #SUNTANS self.flash_status_message("Opening SUNTANS file: %s" % path) try: Spatial.__init__(self, path, _FillValue=self._FillValue) except: Spatial.__init__(self, path, _FillValue=-999999) startvar = 'dv' if dlg.GetFilterIndex() == 1: #UnTRIM self.flash_status_message("Opening UnTRIMS file: %s" % path) #Spatial.__init__(self,path,gridvars=untrim_gridvars,griddims=untrim_griddims) UNTRIMSpatial.__init__(self, path) startvar = 'Mesh2_face_depth' # Populate the drop down menus vnames = self.listCoordVars() self.variable_list.SetItems(vnames) # Update the time drop down list if 'time' in self.__dict__: self.timestr = [ datetime.strftime(tt, '%d-%b-%Y %H:%M:%S') for tt in self.time ] else: # Assume that it is a harmonic-type file self.timestr = self.nc.Constituent_Names.split() self.time_list.SetItems(self.timestr) # Draw the depth if startvar in vnames: self.variable = startvar self.loadData() self.create_figure() def on_load_grid(self, event): dlg = wx.DirDialog(self, message="Open SUNTANS grid from folder...", defaultPath=os.getcwd(), style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() # Initialise the class self.flash_status_message("Opening SUNTANS grid from folder: %s" % path) Grid.__init__(self, path) # Plot the Grid if 'collection' in self.__dict__: self.axes.collections.remove(self.collection) self.axes, self.collection = self.plotmesh(ax=self.axes, edgecolors='y') # redraw the figure self.canvas.draw() def on_load_ptm(self, event): file_choices = "PTM NetCDF (*.nc)|*.nc|PTM Binary (*_bin.out)|*_bin.out|All Files (*.*)|*.*" dlg = wx.FileDialog(self, message="Open PTM file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style=wx.FD_MULTIPLE) if dlg.ShowModal() == wx.ID_OK: self.plot_type = 'particles' path = dlg.GetPath() # Initialise the class if dlg.GetFilterIndex() == 0: #SUNTANS self.flash_status_message("Opening PTM netcdf file: %s" % path) self.PTM = PtmNC(path) elif dlg.GetFilterIndex() == 1: #PTM self.flash_status_message("Opening PTM binary file: %s" % path) self.PTM = PtmBin(path) self.Nt = self.PTM.nt # Update the time drop down list self.timestr = [ datetime.strftime(tt, '%d-%b-%Y %H:%M:%S') for tt in self.PTM.time ] self.time_list.SetItems(self.timestr) # Plot the first time step if 'xlims' in self.__dict__: self.PTM.plot(self.PTM.nt-1,ax=self.axes,xlims=self.xlims,\ ylims=self.ylims,color=self.particlecolor,\ fontcolor='w',markersize=self.particlesize) else: self.PTM.plot(self.PTM.nt-1,ax=self.axes,fontcolor='w',\ color=self.particlecolor,markersize=self.particlesize) # redraw the figure self.canvas.draw() def on_show_edges(self, event): sender = event.GetEventObject() self.showedges = sender.GetValue() # Update the figure self.update_figure() def on_clim_check(self, event): sender = event.GetEventObject() if sender.GetValue() == True: self.autoclim = False self.update_figure() else: self.autoclim = True def on_climlow(self, event): self.clim[0] = event.GetString() #self.update_figure() def on_climhigh(self, event): self.clim[1] = event.GetString() #self.update_figure() def on_select_cmap(self, event): self.cmap = event.GetString() if USECMOCEAN: self.collection.set_cmap(getattr(cm, self.cmap)) else: self.collection.set_cmap(self.cmap) # Update the figure self.update_figure() def on_save_fig(self, event): """ Save a figure of the current scene to a file """ file_choices = " (*.png)|*.png| (*.pdf)|*.pdf |(*.jpg)|*.jpg |(*.eps)|*eps " filters = ['.png', '.pdf', '.png', '.png'] dlg = wx.FileDialog(self, message="Save figure to file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() ext = filters[dlg.GetFilterIndex()] if ext in path: outfile = path else: outfile = path + ext self.fig.savefig(outfile) def on_save_anim(self, event): """ Save an animation of the current scene to a file """ file_choices = "Quicktime (*.mov)|*.mov| (*.gif)|*.gif| (*.avi)|*.avi |(*.mp4)|*.mp4 " filters = ['.mov', '.gif', '.avi', '.mp4'] dlg = wx.FileDialog(self, message="Output animation file...", defaultDir=os.getcwd(), defaultFile="", wildcard=file_choices, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() ext = filters[dlg.GetFilterIndex()] if ext in path: outfile = path else: outfile = path + ext self.flash_status_message("Saving figure to file: %s" % outfile) self.flash_status_message("Saving animation to file: %s" % outfile) # Create the animation #self.tstep = range(self.Nt) # Use all time steps for animation #self.animate(cbar=self.cbar,cmap=self.cmap,\ # xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) def initanim(): if not self.plot_type == 'particles': return (self.title, self.collection) else: return (self.PTM.title, self.PTM.p_handle) def updateScalar(i): if not self.plot_type == 'particles': self.tstep = [i] self.loadData() self.update_figure() return (self.title, self.collection) elif self.plot_type == 'particles': self.PTM.plot(i,ax=self.axes,\ xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) return (self.PTM.title, self.PTM.p_handle) self.anim = animation.FuncAnimation(self.fig, \ updateScalar, init_func = initanim, frames=self.Nt, interval=50, blit=True) if ext == '.gif': self.anim.save(outfile, writer='imagemagick', fps=6) elif ext == '.mp4': print('Saving html5 video...') # Ensures html5 compatibility self.anim.save(outfile,writer='mencoder',fps=6,\ bitrate=3600,extra_args=['-ovc','x264']) # mencoder options #bitrate=3600,extra_args=['-vcodec','libx264']) else: self.anim.save(outfile, writer='mencoder', fps=6, bitrate=3600) # Return the figure back to its status del self.anim self.tstep = self.tindex if not self.plot_type == 'particles': self.loadData() self.update_figure() # Bring up a dialog box dlg2 = wx.MessageDialog(self, 'Animation complete.', "Done", wx.OK) dlg2.ShowModal() dlg2.Destroy() def on_exit(self, event): self.Destroy() def on_about(self, event): msg = """ SUNTANS NetCDF visualization tool *Author: Matt Rayson *Institution: Stanford University *Created: October 2013 """ dlg = wx.MessageDialog(self, msg, "About", wx.OK) dlg.ShowModal() dlg.Destroy() def on_count_cells(self, eveny): msg = "Total 3-D grid cells = %d" % (self.count_cells()) dlg = wx.MessageDialog(self, msg, "No. cells", wx.OK) dlg.ShowModal() dlg.Destroy() def on_overlay_bathy(self, event): # Plot depth contours print('Plotting contours...') self.contourf(z=self.dv, clevs=self.depthlevs,\ ax=self.axes,\ filled=False, colors='0.5', linewidths=0.5, zorder=1e6) print('Done') def on_plot_gridstat(self, event): """ Plot the grid size histogram in a new figure """ matplotlib.pyplot.figure() self.plothist() matplotlib.pyplot.show() def create_status_bar(self): self.statusbar = self.CreateStatusBar() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('')
def map_diversity(): #subpref_avg_fq = rd.read_in_subpref_avg_fq() rg = get_scaled_rg() fig = plt.figure(1) #Custom adjust of the subplots plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) m.drawcoastlines() from shapelib import ShapeFile import dbflib from matplotlib.collections import LineCollection from matplotlib import cm shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') msg = "Out of bounds" color_col = [] for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) x, y = m(lons, lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] num = ["%.2f" % rg[subpref_id]] # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs,antialiaseds=(1,)) lines.set_facecolors(str(rg[subpref_id])) lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) plt.savefig('/home/sscepano/D4D res/allstuff/diversity of travel/diversity_map.png',dpi=500) return
def drawMap(filename,names,totalCount): countries = json.loads(open(filename).read())["features"] for country in countries: name = country["properties"]["name"] polygonList = country["geometry"]["coordinates"] polygonType = country["geometry"]["type"] shpsegs = [] print "Processing %s [%d/%s] ..." % (unicode(name).encode("utf-8"), len(polygonList), polygonType) maxverts = 0 maxindex = 0 counter = 0 for polygon in polygonList: if polygonType == "MultiPolygon": for p in polygon: if len(p) == 1: p = p[0] if p[0] != p[-1]: p.append(p[0]) lons, lats = zip(*p) x, y = m(lons, lats) shpsegs.append(zip(x,y)) if len(x) > maxverts: maxverts = len(x) maxindex = counter counter+=1 else: if len(polygon) == 1: polygon = polygon[0] if polygon[0] != polygon[-1]: polygon.append(polygon[0]) lons, lats = zip(*polygon) x, y = m(lons, lats) shpsegs.append(zip(x,y)) if len(x) > maxverts: maxverts = len(x) maxindex = counter counter+=1 # Compute centroid centroid = Polygon(shpsegs[maxindex]).centroid # Create country shape lines = LineCollection(shpsegs,antialiaseds=(1,)) lines.set_edgecolors('k') lines.set_linewidth(0.5) #import brewer2mpl #colormap = brewer2mpl.get_map('Paired', 'qualitative', 12).mpl_colors colormap = [(0.6509803921568628, 0.807843137254902, 0.8901960784313725), (0.12156862745098039, 0.47058823529411764, 0.7058823529411765), (0.6980392156862745, 0.8745098039215686, 0.5411764705882353), (0.2, 0.6274509803921569, 0.17254901960784313), (0.984313725490196, 0.6039215686274509, 0.6), (0.8901960784313725, 0.10196078431372549, 0.10980392156862745), (0.9921568627450981, 0.7490196078431373, 0.43529411764705883), (1.0, 0.4980392156862745, 0.0), (0.792156862745098, 0.6980392156862745, 0.8392156862745098), (0.41568627450980394, 0.23921568627450981, 0.6039215686274509), (1.0, 1.0, 0.6), (0.6941176470588235, 0.34901960784313724, 0.1568627450980392)] # Add color and label if covered by Safecast if name in names.keys(): color = colormap[(int((float(names[name][0])/totalCount)*12)+1)] lines.set_label("%s - %0.1fK (%d)" % (name, names[name][0]/1000.0, names[name][1]) ) #lines.set_label(name) lines.set_edgecolors(color) lines.set_facecolors(color) label = plt.text(centroid.x, centroid.y, "%d" % names[name][1], fontsize=5, ha='center', va='center', color='k', fontweight='bold') plt.setp(label, path_effects=[PathEffects.withStroke(linewidth=2, foreground="w")]) ax.add_collection(lines)
def contourmap( self, data, ax, cleve, cmp, season_x=0.5, season_y=0.8, case_x=0.02, case_y=0.05, ylabels=None, sidenamefontsize=10, terrain=None, text=None, ): # setup lambert conformal basemap. # lat_1 is first standard parallel. # lat_2 is second standard parallel (defaults to lat_1). # lon_0,lat_0 is central point. # rsphere=(6378137.00,6356752.3142) specifies WGS4 ellipsoid # area_thresh=1000 means don't plot coastline features less # than 1000 km^2 in area. for shapefilepath, segs in self.segs.iteritems(): from matplotlib.collections import LineCollection for seg in segs: lines = LineCollection(seg, antialiaseds=(1, )) lines.set_edgecolors('k') lines.set_linewidth(0.08) ax.add_collection(lines) self.m.drawcoastlines(linewidth=0.08, color='k', antialiased=1, ax=None, zorder=None) self.m.drawstates(linewidth=0.08, color='k') import matplotlib.colors as mc norm = mc.BoundaryNorm(cleve, cmp.N) #norm = mc.BoundaryNorm(cleve, len(cleve)) #cs = self.m.contourf(self.x,self.y,data,cmap=cmp ,norm=norm,extend='max') #,extend='both') cs = self.m.contourf(self.x, self.y, data, cleve, cmap=cmp, norm=norm, extend=self.extend) #,extend='both') if text is not None: ax.text(season_x, season_y, text, verticalalignment='bottom', horizontalalignment='center', transform=ax.transAxes, fontsize=sidenamefontsize, fontweight='bold') if terrain is not None: import matplotlib.cm as cm level_h = range(0, 2000, 200) ct = self.m.contour(self.x, self.y, terrain, level_h, linewidths=0.05, extend='max', colors='k') #,extend='both') for axis in ['top', 'bottom', 'left', 'right']: ax.spines[axis].set_linewidth(0.01) if ylabels: ax.text(case_x, case_y, ylabels, verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, fontsize=sidenamefontsize, fontweight='bold') [i.set_linewidth(0.1) for i in ax.spines.itervalues()] return (cs)
def map_wake_hr(thersholdX): mpl.rcParams['font.size'] = 4.4 ########################################################################################### fig = plt.figure(3) #Custom adjust of the subplots plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) subpref_wake_hr = read_in_subpref_wake_hr(thersholdX) # read the shapefile archive s = m.readshapefile('/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE', 'subpref') max7s = 1 min7s = 10000000 for subpref in subpref_wake_hr.keys(): if subpref_wake_hr[subpref] > max7s: max7s = subpref_wake_hr[subpref] if subpref_wake_hr[subpref] < min7s: min7s = subpref_wake_hr[subpref] max7s = float(max7s) print "max", (max7s) print "min", (min7s) # scaled_weight = defaultdict(int) # for i in range(256): # scaled_weight[i] = defaultdict(int) # for subpref in subpref_wake_hr.keys(): # scaled_weight[subpref] = (subpref_wake_hr[subpref] - min7s) / (max7s - min7s) # values = range(256) # jet = cm = plt.get_cmap('jet') # cNorm = colors.Normalize(vmin=0, vmax=values[-1]) # scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) # define custom colormap, white -> nicered, #E6072A = RGB(0.9,0.03,0.16) cdict = {'red': ( (0.0, 1.0, 1.0), (1.0, 0.9, 1.0) ), 'green':( (0.0, 1.0, 1.0), (1.0, 0.03, 0.0) ), 'blue': ( (0.0, 1.0, 1.0), (1.0, 0.16, 0.0) ) } custom_map = LinearSegmentedColormap('custom_map', cdict, N=33) plt.register_cmap(cmap=custom_map) subpref_coord = read_in_subpref_lonlat() shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) # if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: # raise ValueError,msg x, y = m(lons, lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] print name, subpref_id # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs,antialiaseds=(1,)) colorVal = custom_map(subpref_wake_hr[subpref_id]) # colorVal = scaled_weight[subpef] lines.set_facecolors(colorVal) lines.set_edgecolors('gray') lines.set_linewidth(0.1) ax.add_collection(lines) # data to plot on the map lons = [] lats = [] num = [] for subpref in subpref_wake_hr.iterkeys(): print(subpref) if subpref <> 0 and subpref <> -1: lons.append(subpref_coord[subpref][0]) lats.append(subpref_coord[subpref][1]) num.append(subpref_wake_hr[subpref]) x, y = m(lons, lats) m.scatter(x, y, color='white') for name, xc, yc in zip(num, x, y): # draw the pref name in a yellow (shaded) box plt.text(xc, yc, name) plt.savefig("/home/sscepano/Project7s/D4D/CI/call_wakeup_sleep_hour/subpref_wake_" + str(thersholdX) + "pct.png",dpi=350)
def map_num_users(): mpl.rcParams['font.size'] = 4.4 ########################################################################################### fig = plt.figure(3) #Custom adjust of the subplots plt.subplots_adjust(left=0.05, right=0.95, top=0.90, bottom=0.05, wspace=0.15, hspace=0.05) ax = plt.subplot(111) m = Basemap(llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) subpref_users = read_in_subpref_num_users() # read the shapefile archive s = m.readshapefile( '/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE', 'subpref') max7s = 1 min7s = 10000000 for subpref in subpref_users.keys(): if subpref_users[subpref] > max7s: max7s = subpref_users[subpref] if subpref_users[subpref] < min7s: min7s = subpref_users[subpref] max7s = float(max7s) print "max", (max7s) print "min", (min7s) scaled_weight = defaultdict(int) for i in range(256): scaled_weight[i] = defaultdict(int) for subpref in subpref_users.keys(): scaled_weight[subpref] = (subpref_users[subpref] - min7s) / (max7s - min7s) # values = range(256) # jet = cm = plt.get_cmap('jet') # cNorm = colors.Normalize(vmin=0, vmax=values[-1]) # scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) # define custom colormap, white -> nicered, #E6072A = RGB(0.9,0.03,0.16) cdict = { 'red': ((0.0, 1.0, 1.0), (1.0, 0.9, 1.0)), 'green': ((0.0, 1.0, 1.0), (1.0, 0.03, 0.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 0.16, 0.0)) } custom_map = LinearSegmentedColormap('custom_map', cdict, N=10000) plt.register_cmap(cmap=custom_map) subpref_coord = read_in_subpref_lonlat() shp = ShapeFile( r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open( r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) #print shp_object for ring in range(rings): print ring lons, lats = zip(*verts[ring]) # if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: # raise ValueError,msg x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring == 0: shapedict = dbf.read_record(npoly) print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] # print name, subpref_id # add information about ring number to dictionary. shapedict['RINGNUM'] = ring + 1 shapedict['SHAPENUM'] = npoly + 1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs, antialiaseds=(1, )) colorVal = custom_map(subpref_users[subpref_id]) # colorVal = scaled_weight[subpef] lines.set_facecolors(colorVal) lines.set_edgecolors('gray') lines.set_linewidth(0.1) ax.add_collection(lines)
def map_commutes(G): import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import matplotlib as mpl mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. from shapelib import ShapeFile import dbflib from matplotlib.collections import LineCollection from matplotlib import cm ########################################################################################### fig = plt.figure(3) #Custom adjust of the subplots plt.subplots_adjust(left=0.05, right=0.95, top=0.90, bottom=0.05, wspace=0.15, hspace=0.05) ax = plt.subplot(111) m = Basemap(projection='cyl',\ llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ # projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) # read subpref coordinates subpref_coord = read_subpref_lonlat() shp = ShapeFile( r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open( r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) # if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: # raise ValueError,msg x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] # add information about ring number to dictionary. shapedict['RINGNUM'] = ring + 1 shapedict['SHAPENUM'] = npoly + 1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs, antialiaseds=(1, )) # lines.set_facecolors(col[subpref_id]) lines.set_edgecolors('k') lines.set_linewidth(0.2) ax.add_collection(lines) if G.has_node(-1): G.remove_node(-1) if G.has_node(0): G.remove_node(0) max7s = 1 min7s = 10000000 for u, v, d in G.edges(data=True): if d['weight'] > max7s: max7s = d['weight'] if d['weight'] < min7s: min7s = d['weight'] max7s = float(max7s) print "max", (max7s) print "min", (min7s) scaled_weight = defaultdict(int) for i in range(256): scaled_weight[i] = defaultdict(int) for u, v, d in G.edges(data=True): scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s) for u, v, d in G.edges(data=True): # lo = [] # la = [] # lo.append(subpref_coord[u][0]) # lo.append(subpref_coord[v][0]) # la.append(subpref_coord[u][1]) # la.append(subpref_coord[v][1]) # x, y = m(lo, la) # linewidth7s = scaled_weight[u][v] * 2.5 + 0.25 # m.plot(x,y, linewidth= linewidth7s) # if linewidth7s > 1: # print (linewidth7s) linewidth7s = scaled_weight[u][v] * 2.5 + 0.25 m.drawgreatcircle(subpref_coord[u][0], subpref_coord[u][1], \ subpref_coord[v][0], subpref_coord[v][1], linewidth= linewidth7s, color='r') m.drawcoastlines() m.fillcontinents() plt.savefig( '/home/sscepano/Project7s/D4D/CI/urban_rural/home_work/OUTPUT_files/maps/hw_commuting_cur.png', dpi=700) #plt.show() ###################################################################################################3 return
def map_commutes(G): mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. ########################################################################################### fig = plt.figure(3) #Custom adjust of the subplots plt.subplots_adjust(left=0.05, right=0.95, top=0.90, bottom=0.05, wspace=0.15, hspace=0.05) ax = plt.subplot(111) m = Basemap(projection='cyl',\ llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ # projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) # read subpref coordinates subpref_coord = read_in_subpref_lonlat() shp = ShapeFile( r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open( r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) # if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: # raise ValueError,msg x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] # add information about ring number to dictionary. shapedict['RINGNUM'] = ring + 1 shapedict['SHAPENUM'] = npoly + 1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs, antialiaseds=(1, )) # lines.set_facecolors(col[subpref_id]) lines.set_edgecolors('k') lines.set_linewidth(0.2) ax.add_collection(lines) if G.has_node(-1): G.remove_node(-1) if G.has_node(0): G.remove_node(0) ########################################################################################################### ### this is the main part: scale weights of # commuters, use colormap by work location and then plot ### all or just the routes with more that 10 commutes ########################################################################################################### max7s = 1 min7s = 10000000 for u, v, d in G.edges(data=True): if d['weight'] > max7s: max7s = d['weight'] if d['weight'] < min7s: min7s = d['weight'] max7s = float(max7s) print "max", (max7s) print "min", (min7s) scaled_weight = defaultdict(int) for i in range(256): scaled_weight[i] = defaultdict(int) for u, v, d in G.edges(data=True): scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s) values = range(256) jet = cm = plt.get_cmap('jet') cNorm = colors.Normalize(vmin=0, vmax=values[-1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) for u, v, d in G.edges(data=True): # lo = [] # la = [] # lo.append(subpref_coord[u][0]) # lo.append(subpref_coord[v][0]) # la.append(subpref_coord[u][1]) # la.append(subpref_coord[v][1]) # x, y = m(lo, la) # linewidth7s = scaled_weight[u][v] * 2.5 + 0.25 # m.plot(x,y, linewidth= linewidth7s) # if linewidth7s > 1: # print (linewidth7s) if d['weight'] >= 10: colorVal = scalarMap.to_rgba(values[v]) linewidth7s = scaled_weight[u][v] * 2.5 + 0.35 ########################################################################################################### ### no scaling vs scaling the width of the line ########################################################################################################### # linewidth7s = d['weight'] / 10 m.drawgreatcircle(subpref_coord[u][0], subpref_coord[u][1], \ subpref_coord[v][0], subpref_coord[v][1], linewidth= linewidth7s, color=colorVal) m.drawcoastlines() #m.fillcontinents() plt.savefig( '/home/sscepano/Project7s/D4D/CI/urban_rural/home_work/OUTPUT_files/maps/hw_commuting_colored_by_work_gr10commuters.png', dpi=700) #plt.show() ###################################################################################################3 return
def plot_streets_network(edges_index, edges, vertices, shapes, order=None, color_vertices=None, color_edges=None, ax=None, **kwargs): """ Plot the network based on `basemap <http://matplotlib.org/basemap/>`_. @param edges_index index of the edges in shapes @param edges list of tuple(v1, v2) in array of vertices @param vertices list of vertices coordinates @param shapes streets @param order list of edges composing a path (eulerian path) @param color_vertices dictionary ``{ vertex_index: color }``, changes the color associated to each vertex (black by default) @param color_edges dictionary ``{ edges_index: color }``, changes the color associated to each edge (black by default) @param ax axis or None @param kwargs parameter used to create the plot is ax is None @return ax *kwargs* may contain parameters: *color_v*, *color_e*, *size_v*, *size_e*, *size_c*, *size_et*. If *order* is not None, the function replaces the edge index by its position in this array. if *color_vertices* is equal to `'odd'`, the function computes the degree of each vertex and choose a different color for odd (yellow) and even degrees (black). """ from mpl_toolkits.basemap import Basemap import numpy from matplotlib.collections import LineCollection import matplotlib.pyplot as plt params = ["color_v", "color_e", "size_v", "size_e", "size_c", "size_et"] if ax is None: options = {k: v for k, v in kwargs.items() if k not in params} fig, ax = plt.subplots(**options) x1, x2 = min(_[0] for _ in vertices), max(_[0] for _ in vertices) y1, y2 = min(_[1] for _ in vertices), max(_[1] for _ in vertices) dx, dy = (x2 - x1) * 0.2, (y2 - y1) * 0.2 x1 -= dx x2 += dx y1 -= dy y2 += dy m = Basemap(resolution='i', projection='merc', llcrnrlat=y1, urcrnrlat=y2, llcrnrlon=x1, urcrnrlon=x2, lat_ts=(y1 + y2) / 2, ax=ax) m.drawcountries(linewidth=0.5) m.drawcoastlines(linewidth=0.5) for n in edges_index: sh = shapes[n] geo_points = sh.points lons = [_[0] for _ in geo_points] lats = [_[1] for _ in geo_points] data = numpy.array(m(lons, lats)).T segs = [data, ] lines = LineCollection(segs, antialiaseds=(1,)) if color_edges is not None: ecolor = color_edges.get(n, "black") else: ecolor = "black" lines.set_edgecolors(ecolor) lines.set_linewidth(kwargs.get('size_e', 2)) ax.add_collection(lines) mx, my = (lons[0] + lons[-1]) / 2, (lats[0] + lats[-1]) / 2 gx, gy = m(mx, my) if order is None: ax.text(gx, gy, "e%d" % n, color=kwargs.get('color_e', "blue")) else: pos = [i + 1 for i, v in enumerate(order) if v == n] if len(pos) > 0: pos = [str(_) for _ in pos] ax.text(gx, gy, ",".join(pos), size=kwargs.get("size_et", 12), color=kwargs.get('color_e', "blue")) if color_vertices == "odd": count = {} for a, b in edges: count[a] = count.get(a, 0) + 1 count[b] = count.get(b, 0) + 1 color_vertices = {k: ('yellow' if v % 2 == 1 else 'black') for k, v in count.items()} for n, (a, b) in enumerate(vertices): gx, gy = m(a, b) color = color_vertices.get(n, 'black') if color_vertices else 'black' c = plt.Circle((gx, gy), kwargs.get('size_c', 5), color=color) ax.add_artist(c) ax.text(gx, gy, "v%d" % n, size=kwargs.get('size_v', 12), color=kwargs.get('color_v', "red")) return ax
def map_communities_and_commutes(G): import networkx as nx G_mod = nx.read_gml("/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/total_commuting_G_10com_775_269_v2.gml") col = [str]*256 for i in range(256): col[i] = 'w' for node in G_mod.nodes_iter(data=True): #print node[1]['label'] col_gephi = node[1]['graphics']['fill'] while (len(col_gephi) < 7): col_gephi += '0' col[int(float(node[1]['label']))] = col_gephi import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import matplotlib as mpl mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. from shapelib import ShapeFile import dbflib from matplotlib.collections import LineCollection from matplotlib import cm ########################################################################################### fig = plt.figure(3) #Custom adjust of the subplots plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) m.drawcoastlines() shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) # if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: # raise ValueError,msg x, y = m(lons, lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] #color_col # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs,antialiaseds=(1,)) lines.set_facecolors(col[subpref_id]) lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) from collections import defaultdict if G.has_node(-1): G.remove_node(-1) max7s = 1 min7s = 1 for u,v,d in G.edges(data=True): if d['weight'] > max7s: max7s = d['weight'] if d['weight'] < min7s: min7s = d['weight'] max7s = float(max7s) print max7s print min7s scaled_weight = defaultdict(int) for i in range(256): scaled_weight[i] = defaultdict(int) for u,v,d in G.edges(data=True): scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s) for u, v, d in G.edges(data=True): lo = [] la = [] lo.append(lons[u]) lo.append(lons[v]) la.append(lats[u]) la.append(lats[v]) x, y = m(lo, la) linewidth7s = scaled_weight[u][v] * 6.5 + 0.15 m.plot(x,y, linewidth= linewidth7s) if linewidth7s > 1: print linewidth7s plt.savefig('/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/maps/mod_classes_10com_775_269_v2.png',dpi=1000) #plt.show() ###################################################################################################3 return
def plot_gspan_res(G, subpref_id, color_val): fig = plt.figure(subpref_id) #Custom adjust of the subplots plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) # read the shapefile archive s = m.readshapefile('/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE', 'subpref') m.drawcoastlines() shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') msg = "Out of bounds" color_col = [] for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) x, y = m(lons, lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id2 = shapedict["ID_SP"] #color_col # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) lines = LineCollection(shpsegs,antialiaseds=(1,)) if subpref_id == subpref_id2: lines.set_facecolors('g') lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) # data to plot on the map lons = [int]*256 lats = [int]*256 num = [] # read in coordinates fo subprefs file_name2 = "/home/sscepano/DATA SET7S/D4D/SUBPREF_POS_LONLAT.TSV" f2 = open(file_name2, 'r') # read subpref coordinates subpref_coord = {} for line in f2: subpref_id, lon, lat = line.split('\t') lon = float(lon) lat = float(lat) subpref_id = int(subpref_id) subpref_coord.keys().append(subpref_id) subpref_coord[subpref_id] = (lon, lat) f2.close() # if wanna plot number of users whose this is home subpref for subpref in range(1,256): lons[subpref] = subpref_coord[subpref][0] lats[subpref] = subpref_coord[subpref][1] for u, v, d in G.edges(data=True): lo = [] la = [] lo.append(lons[u]) lo.append(lons[v]) la.append(lats[u]) la.append(lats[v]) x, y = m(lo, la) m.plot(x,y, color = color_val) return plt
class SunPlotPy(Spatial, QMainWindow): """ The main frame of the application """ title = 'sunplot(py)' # Plotting options autoclim = True showedges = False bgcolor = 'k' textcolor = 'w' cmap = 'RdBu' particlesize = 1.8 particlecolor = 'm' # other flags collectiontype = 'cells' oldcollectiontype = 'cells' # tindex = 0 depthlevs = [0., 10., 100., 200., 300., 400., 500.,\ 1000.,2000.,3000.,4000.,5000] _FillValue = 999999 def __init__(self, parent=None): #wx.Frame.__init__(self, None, -1, self.title) QMainWindow.__init__(self, parent) #super(SunPlotPy, self).__init__(parent) self.create_menu() #self.create_status_bar() self.create_main_panel() #self.draw_figure() def create_menu(self): self.file_menu = self.menuBar().addMenu("&File") ### # File Menu ### # Load a hydro output file load_file_action = self.create_action("&Open file",\ shortcut="ctrl-o", slot=self.on_open_file, tip="open netcdf file") load_grid_action = self.create_action("&Open grid",\ shortcut="ctrl-g", slot=self.on_load_grid, tip="open suntans grid") save_anim_action = self.create_action("&Save animation",\ shortcut="ctrl-a", slot=self.on_save_anim, tip="animate current scene") quit_action = self.create_action("&Exit",\ shortcut="ctrl-x", slot=self.close, tip="Close the application") self.add_actions(self.file_menu, (load_file_action, load_grid_action,\ save_anim_action, None, quit_action)) # self.Bind(wx.EVT_MENU, self.on_open_file, m_expt) ### # Tools menu ### self.tools_menu = self.menuBar().addMenu("&Tools") ### # File Menu ### # Load a hydro output file load_stat_action = self.create_action("&Plot grid size statistics",\ slot=self.on_plot_gridstat, tip="grid stats") self.add_actions(self.tools_menu, (load_stat_action, )) # # Load a grid file # m_grid = menu_file.Append(-1, "&Load grid\tCtrl-G", "Load SUNTANS grid from folder") # self.Bind(wx.EVT_MENU, self.on_load_grid, m_grid) # # Load a particle file # m_part = menu_file.Append(-1, "&Load PTM file\tCtrl-Shift-P", "Load a PTM file") # self.Bind(wx.EVT_MENU, self.on_load_ptm, m_part) # # Save current scene as an animation # m_anim = menu_file.Append(-1,"&Save animation of current scene\tCtrl-S","Save animation") # self.Bind(wx.EVT_MENU, self.on_save_anim, m_anim) # # Save the current figure # m_prin = menu_file.Append(-1,"&Print current scene\tCtrl-P","Save figure") # self.Bind(wx.EVT_MENU, self.on_save_fig, m_prin) # menu_file.AppendSeparator() # # Exit # m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") # self.Bind(wx.EVT_MENU, self.on_exit, m_exit) # ### # # Tools menu # ### # menu_tools = wx.Menu() # m_gridstat = menu_tools.Append(-1, "&Plot grid size statistics", "SUNTANS grid size") # self.Bind(wx.EVT_MENU, self.on_plot_gridstat, m_gridstat) # m_countcells = menu_tools.Append(-1, "&Count # grid cells", "Grid cell count") # self.Bind(wx.EVT_MENU, self.on_count_cells, m_countcells) # m_overlaybathy = menu_tools.Append(-1, "&Overlay depth contours", "Depth overlay") # self.Bind(wx.EVT_MENU, self.on_overlay_bathy, m_overlaybathy) # # ### # # Help Menu # ### # menu_help = wx.Menu() # m_about = menu_help.Append(-1, "&About\tF1", "About the demo") # self.Bind(wx.EVT_MENU, self.on_about, m_about) # # # # Add all of the menu bars # self.menubar.Append(menu_file, "&File") # self.menubar.Append(menu_tools, "&Tools") # self.menubar.Append(menu_help, "&Help") # self.SetMenuBar(self.menubar) def add_actions(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) def create_action( self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, ): #signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(":/%s.png" % icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: #self.connect(action, SIGNAL(signal), slot) # Qt5 style action.triggered.connect(slot) if checkable: action.setCheckable(True) return action def create_main_panel(self): """ Creates the main panel with all the controls on it: * mpl canvas * mpl navigation toolbar * Control panel for interaction """ self.panel = QWidget() # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.dpi = 100 #self.fig = Figure((7.0, 6.0), dpi=self.dpi,facecolor=self.bgcolor) self.fig = Figure((7.0, 6.0), dpi=self.dpi) #self.canvas = FigCanvas(self.panel, -1, self.fig) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.panel) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # self.axes = self.fig.add_subplot(111) #SetAxColor(self.axes,self.textcolor,self.bgcolor) # Bind the 'pick' event for clicking on one of the bars # #self.canvas.mpl_connect('pick_event', self.on_pick) ######### ## Create widgets ######### self.variable_list = QComboBox() self.variable_list.addItem("Select a variable...") self.variable_list.activated[str].connect(self.on_select_variable) self.time_list = QComboBox() self.time_list.addItem("Select a time...") self.time_list.activated[int].connect(self.on_select_time) self.depthlayer_list = QComboBox() self.depthlayer_list.addItem("Select a vertical layer...") self.depthlayer_list.activated[int].connect(self.on_select_depth) self.show_edge_check = QCheckBox('Show Edges', self) #self.show_edge_check.toggle() self.show_edge_check.stateChanged.connect(self.on_show_edges) cmaps = list(matplotlib.cm.datad.keys()) cmaps.sort() self.colormap_list = QComboBox() self.colormap_list.clear() self.colormap_list.addItems(cmaps) self.colormap_list.activated[str].connect(self.on_select_cmap) self.clim_check = QCheckBox('Manual color limits', self) #self.show_edge_check.toggle() self.clim_check.stateChanged.connect(self.on_clim_check) #self.clim_check = wx.CheckBox(self.panel, -1, # "Manual color limits ", # style=wx.ALIGN_RIGHT) #self.clim_check.Bind(wx.EVT_CHECKBOX, self.on_clim_check) self.climlow = QLineEdit() self.climlow.textChanged[str].connect(self.on_climlow) self.climhigh = QLineEdit() self.climhigh.textChanged[str].connect(self.on_climhigh) ## Labels #self.variable_label = wx.StaticText(self.panel, -1,"Variable:",size=(200,-1)) #self.time_label = wx.StaticText(self.panel, -1,"Time step:",size=(200,-1)) #self.depth_label = wx.StaticText(self.panel, -1,"Vertical level:",size=(200,-1)) # Create the navigation toolbar, tied to the canvas # self.toolbar = NavigationToolbar(self.canvas, self) #self.toolbar.toolitems[8][3]='my_save_fig' #def my_save_fig(self,*args): # print 'saving figure' ## return "break" ######### # Layout with box sizers ######### hbox = QHBoxLayout() for w in [self.variable_list, self.time_list, self.depthlayer_list]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) hbox1 = QHBoxLayout() for w in [ self.show_edge_check, self.colormap_list, self.clim_check, self.climlow, self.climhigh ]: hbox1.addWidget(w) hbox1.setAlignment(w, Qt.AlignVCenter) self.vbox = QVBoxLayout() self.vbox.addWidget(self.canvas) self.vbox.addWidget(self.toolbar) self.vbox.addLayout(hbox) self.vbox.addLayout(hbox1) self.panel.setLayout(self.vbox) self.setCentralWidget(self.panel) # ########### ## Event functions ########### def create_figure(self): """ Creates the figure """ # Find the colorbar limits if unspecified if self.autoclim: self.clim = [self.data.min(), self.data.max()] self.climlow.setText('%3.1f' % self.clim[0]) self.climhigh.setText('%3.1f' % self.clim[1]) if 'collection' in self.__dict__: #self.collection.remove() self.axes.collections.remove(self.collection) else: # First call - set the axes limits self.axes.set_aspect('equal') self.axes.set_xlim(self.xlims) self.axes.set_ylim(self.ylims) if self.collectiontype == 'cells': self.collection = PolyCollection(self.xy, cmap=self.cmap) self.collection.set_array(np.array(self.data[:])) if not self.showedges: self.collection.set_edgecolors( self.collection.to_rgba(np.array((self.data[:])))) elif self.collectiontype == 'edges': xylines = [self.xp[self.edges], self.yp[self.edges]] linesc = [ list(zip(xylines[0][ii, :], xylines[1][ii, :])) for ii in range(self.Ne) ] self.collection = LineCollection(linesc, array=np.array(self.data[:]), cmap=self.cmap) self.collection.set_clim(vmin=self.clim[0], vmax=self.clim[1]) self.axes.add_collection(self.collection) self.title = self.axes.set_title(self.genTitle(), color=self.textcolor) self.axes.set_xlabel('Easting [m]') self.axes.set_ylabel('Northing [m]') # create a colorbar if 'cbar' not in self.__dict__: self.cbar = self.fig.colorbar(self.collection) #SetAxColor(self.cbar.ax.axes,self.textcolor,self.bgcolor) else: #pass print('Updating colorbar...') #self.cbar.check_update(self.collection) self.cbar.on_mappable_changed(self.collection) self.canvas.draw() def update_figure(self): if self.autoclim: self.clim = [self.data.min(), self.data.max()] self.climlow.setText('%3.1f' % self.clim[0]) self.climhigh.setText('%3.1f' % self.clim[1]) else: self.clim = [float(self.climlow.text()),\ float(self.climhigh.text())] # check whether it is cell or edge type if self.hasDim(self.variable, self.griddims['Ne']): self.collectiontype = 'edges' elif self.hasDim(self.variable, self.griddims['Nc']): self.collectiontype = 'cells' # Create a new figure if the variable has gone from cell to edge of vice # versa if not self.collectiontype == self.oldcollectiontype: self.create_figure() self.oldcollectiontype = self.collectiontype self.collection.set_array(np.array(self.data[:])) self.collection.set_clim(vmin=self.clim[0], vmax=self.clim[1]) # Cells only if self.collectiontype == 'cells': if not self.showedges: self.collection.set_edgecolors( self.collection.to_rgba(np.array((self.data[:])))) else: self.collection.set_edgecolors('k') self.collection.set_linewidths(0.2) # Update the title self.title = self.axes.set_title(self.genTitle(), color=self.textcolor) #Update the colorbar self.cbar.update_normal(self.collection) # redraw the figure self.canvas.draw() #def on_pick(self, event): # # The event received here is of the type # # matplotlib.backend_bases.PickEvent # # # # It carries lots of information, of which we're using # # only a small amount here. # # # box_points = event.artist.get_bbox().get_points() # msg = "You've clicked on a bar with coords:\n %s" % box_points # # dlg = wx.MessageDialog( # self, # msg, # "Click!", # wx.OK | wx.ICON_INFORMATION) # dlg.ShowModal() # dlg.Destroy() # def on_select_variable(self, event): #vname = event.GetString() vname = event #self.flash_status_message("Selecting variable: %s"%vname) # update the spatial object and load the data self.variable = vname self.loadData(variable=self.variable) # Check if the variable has a depth coordinate depthstr = [''] # If so populate the vertical layer box if self.hasDim(self.variable, self.griddims['Nk']): depthstr = ['%3.1f' % self.z_r[k] for k in range(self.Nkmax)] depthstr += ['surface', 'seabed'] elif self.hasDim(self.variable, 'Nkw'): depthstr = ['%3.1f' % self.z_w[k] for k in range(self.Nkmax + 1)] self.depthlayer_list.clear() self.depthlayer_list.addItems(depthstr) # Update the plot self.update_figure() def on_select_time(self, event): self.tindex = event # # Update the object time index and reload the data #if self.plot_type=='hydro': if not self.tstep == self.tindex: self.tstep = self.tindex self.loadData() #self.flash_status_message("Selecting variable: %s..."%event.GetString()) # Update the plot self.update_figure() #elif self.plot_type=='particles': # self.PTM.plot(self.tindex,ax=self.axes,\ # xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) # # self.canvas.draw() def on_select_depth(self, event): print(event) kindex = event if not self.klayer[0] == kindex: # Check if its the seabed or surface value if kindex >= self.Nkmax: kindex = event.GetString() self.klayer = [kindex] self.loadData() #self.flash_status_message("Selecting depth: %s..."%event.GetString()) # Update the plot self.update_figure() def on_open_file(self, event): file_choices = "SUNTANS NetCDF (*.nc);;All Files (*.*)" dlg = QFileDialog.getOpenFileNames(self, "Open SUNTANS file...", "", file_choices) path = dlg[0] if len(path) == 0: return self.statusBar().showMessage("Opening SUNTANS file: %s" % path) try: Spatial.__init__(self, path, _FillValue=self._FillValue) except: Spatial.__init__(self, path, _FillValue=-999999) startvar = 'dv' self.statusBar().clearMessage() # Populate the drop down menus vnames = self.listCoordVars() self.variable_list.clear() self.variable_list.addItems(vnames) # Update the time drop down list if 'time' in self.__dict__: self.timestr = [ datetime.strftime(tt, '%d-%b-%Y %H:%M:%S') for tt in self.time ] else: # Assume that it is a harmonic-type file self.timestr = self.nc.Constituent_Names.split() self.time_list.clear() self.time_list.addItems(self.timestr) # Draw the depth if startvar in vnames: self.variable = startvar self.loadData() self.create_figure() def on_load_grid(self, event): dir_ = QFileDialog.getExistingDirectory(None, 'Select a SUNTANS grid folder:',\ '~/', QFileDialog.ShowDirsOnly) print(dir_) if dir_ is not None: path = dir_ # Initialise the class #self.flash_status_message("Opening SUNTANS grid from folder: %s" % path) Grid.__init__(self, path) # Plot the Grid if 'collection' in self.__dict__: self.axes.collections.remove(self.collection) self.axes, self.collection = self.plotmesh(ax=self.axes, edgecolors='y') # redraw the figure self.canvas.draw() #def on_load_ptm(self, event): # file_choices = "PTM NetCDF (*.nc)|*.nc|PTM Binary (*_bin.out)|*_bin.out|All Files (*.*)|*.*" # # dlg = wx.FileDialog( # self, # message="Open PTM file...", # defaultDir=os.getcwd(), # defaultFile="", # wildcard=file_choices, # style= wx.FD_MULTIPLE) # # if dlg.ShowModal() == wx.ID_OK: # self.plot_type = 'particles' # path = dlg.GetPath() # # Initialise the class # if dlg.GetFilterIndex() == 0: #SUNTANS # self.flash_status_message("Opening PTM netcdf file: %s" % path) # self.PTM = PtmNC(path) # elif dlg.GetFilterIndex() == 1: #PTM # self.flash_status_message("Opening PTM binary file: %s" % path) # self.PTM = PtmBin(path) # self.Nt = self.PTM.nt # # # Update the time drop down list # self.timestr = [datetime.strftime(tt,'%d-%b-%Y %H:%M:%S') for tt in self.PTM.time] # self.time_list.SetItems(self.timestr) # # Plot the first time step # if self.__dict__.has_key('xlims'): # self.PTM.plot(self.PTM.nt-1,ax=self.axes,xlims=self.xlims,\ # ylims=self.ylims,color=self.particlecolor,\ # fontcolor='w',markersize=self.particlesize) # else: # self.PTM.plot(self.PTM.nt-1,ax=self.axes,fontcolor='w',\ # color=self.particlecolor,markersize=self.particlesize) # # redraw the figure # self.canvas.draw() # def on_show_edges(self, event): if event > 0: self.showedges = True else: self.showedges = False # Update the figure self.update_figure() def on_clim_check(self, event): if event > 0: self.autoclim = False self.update_figure() else: self.autoclim = True def on_climlow(self, event): try: self.clim[0] = float(event) except: return # do nothing # self.clim[0] = event.GetString() # #self.update_figure() def on_climhigh(self, event): try: self.clim[1] = float(event) except: return # do nothing # print event # self.clim[1] = event.GetString() # #self.update_figure() def on_select_cmap(self, event): self.cmap = event self.collection.set_cmap(self.cmap) # Update the figure self.update_figure() #def on_save_fig(self,event): # """ # Save a figure of the current scene to a file # """ # file_choices = " (*.png)|*.png| (*.pdf)|*.pdf |(*.jpg)|*.jpg |(*.eps)|*eps " # filters=['.png','.pdf','.png','.png'] # # dlg = wx.FileDialog( # self, # message="Save figure to file...", # defaultDir=os.getcwd(), # defaultFile="", # wildcard=file_choices, # style= wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) # if dlg.ShowModal() == wx.ID_OK: # path = dlg.GetPath() # ext = filters[dlg.GetFilterIndex()] # if ext in path: # outfile=path # else: # outfile = path+ext # self.fig.savefig(outfile) # def on_save_anim(self, event): """ Save an animation of the current scene to a file """ #file_choices = "Quicktime (*.mov)|*.mov| (*.gif)|*.gif| (*.avi)|*.avi |(*.mp4)|*.mp4 " #filters=['.mov','.gif','.avi','.mp4'] filters = "Movie formats (*.mp4 *.avi *.gif);;All files (*.*)" dir_ = QFileDialog.getSaveFileName(None, 'Save animation to file:',\ '~/', filters) print(dir_) #dlg = wx.FileDialog( # self, # message="Output animation file...", # defaultDir=os.getcwd(), # defaultFile="", # wildcard=file_choices, # style= wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dir_ is not None: outfile = dir_[0] ext = outfile[-4::] # Create the animation #self.tstep = range(self.Nt) # Use all time steps for animation #self.animate(cbar=self.cbar,cmap=self.cmap,\ # xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) def initanim(): return (self.title, self.collection) #if not self.plot_type=='particles': # return (self.title, self.collection) #else: # return (self.PTM.title,self.PTM.p_handle) def updateScalar(i): self.tstep = [i] self.loadData() self.update_figure() return (self.title, self.collection) #if not self.plot_type=='particles': # self.tstep=[i] # self.loadData() # self.update_figure() # return (self.title,self.collection) #elif self.plot_type=='particles': # self.PTM.plot(i,ax=self.axes,\ # xlims=self.axes.get_xlim(),ylims=self.axes.get_ylim()) # return (self.PTM.title,self.PTM.p_handle) self.anim = animation.FuncAnimation(self.fig, \ updateScalar, init_func = initanim, frames=self.Nt, interval=50, blit=True) if ext == '.gif': self.anim.save(outfile, writer='imagemagick', fps=6) elif ext == '.mp4': print('Saving html5 video...') # Ensures html5 compatibility self.anim.save(outfile,fps=6,\ writer='ffmpeg',\ bitrate=3600,extra_args=['-vcodec','libx264']) #writer='mencoder', #bitrate=3600,extra_args=['-ovc','x264']) # mencoder options else: self.anim.save(outfile, writer='mencoder', fps=6, bitrate=3600) # Return the figure back to its status del self.anim self.tstep = self.tindex self.loadData() self.update_figure() print('Finished saving animation to %s' % outfile) print(72 * '#') #if not self.plot_type=='particles': # self.loadData() # self.update_figure() # Bring up a dialog box #dlg2= wx.MessageDialog(self, 'Animation complete.', "Done", wx.OK) #dlg2.ShowModal() #dlg2.Destroy() #def on_exit(self, event): # self.Destroy() # #def on_about(self, event): # msg = """ SUNTANS NetCDF visualization tool # # *Author: Matt Rayson # *Institution: Stanford University # *Created: October 2013 # """ # dlg = wx.MessageDialog(self, msg, "About", wx.OK) # dlg.ShowModal() # dlg.Destroy() #def on_count_cells(self,eveny): # msg = "Total 3-D grid cells = %d"%(self.count_cells()) # dlg = wx.MessageDialog(self, msg, "No. cells", wx.OK) # dlg.ShowModal() # dlg.Destroy() #def on_overlay_bathy(self,event): # # Plot depth contours # print 'Plotting contours...' # self.contourf(z=self.dv, clevs=self.depthlevs,\ # ax=self.axes,\ # filled=False, colors='0.5', linewidths=0.5, zorder=1e6) # print 'Done' def on_plot_gridstat(self, event): """ Plot the grid size histogram in a new figure """ matplotlib.pyplot.figure() self.plothist() matplotlib.pyplot.show()
shadowlons = [ squarecorner[0].x, squarecorner[1].x, squarecorner[2].x, squarecorner[3].x ] shadowlats = [ squarecorner[0].y, squarecorner[1].y, squarecorner[2].y, squarecorner[3].y ] x, y = m(shadowlons, shadowlats) shpsegs = [] shpsegs.append(list(zip(x, y))) lines = LineCollection(shpsegs, antialiaseds=(1, )) #不可航行区域 if (squareprolist[plotsquareCount].isNavigonal == False): lines.set_facecolors(cm.jet(0.1)) lines.set_edgecolors('g') lines.set_linewidth(0.6) lines.set_alpha(0.6) #设置透明度 ax.add_collection(lines) #绘制不可行区域 else: lines.set_facecolors(cm.jet(0.02)) lines.set_edgecolors('b') lines.set_linewidth(1.2) #lines.set_alpha(0.1) #设置透明度 # 设置颜色深度,权重越大深度越大 weight = Naviweight.get(squareprolist[plotsquareCount].offsetCoord, 1) if weight < 1: weight = 1 if weight > 10: weight = 10
shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) lines = LineCollection(shpsegs,antialiaseds=(1,)) if subpref_id <> 60: colorVal = scalarMap.to_rgba(values[region_pole[subpref_region[subpref_id]]]) else: colorVal = 'y' print name, subpref_id, colorVal lines.set_facecolors(colorVal) lines.set_edgecolors('gray') lines.set_linewidth(0.1) ax.add_collection(lines) # data to plot on the map lons = [] lats = [] num = [] # if wanna plot subpref ids only for subpref in range(1,256): lons.append(subpref_coord[subpref][0]) lats.append(subpref_coord[subpref][1]) num.append(subpref) ###show or hinde subpref ids
def map_G(G): import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import matplotlib.cm as cmx import matplotlib as mpl mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. from shapelib import ShapeFile import dbflib from matplotlib.collections import LineCollection from matplotlib import cm import matplotlib.colors as colors ########################################################################################### fig = plt.figure(3) #Custom adjust of the subplots plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(projection='cyl',\ llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ # projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) # read subpref coordinates subpref_coord = read_in_subpref_lonlat() shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) # if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: # raise ValueError,msg x, y = m(lons, lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs,antialiaseds=(1,)) # lines.set_facecolors(col[subpref_id]) lines.set_edgecolors('gray') lines.set_linewidth(0.1) ax.add_collection(lines) if G.has_node(-1): G.remove_node(-1) if G.has_node(0): G.remove_node(0) ########################################################################################################### ### this is the main part: scale weights of # commuters, use colormap by work location and then plot ### all or just the routes with more that 10 commutes ########################################################################################################### # max7s = 0 # min7s = 10000000 # for u,v,d in G.edges(data=True): # if d['weight'] > max7s: # max7s = d['weight'] # if d['weight'] < min7s: # min7s = d['weight'] # # max7s = float(max7s) # print "max", (max7s) # print "min", (min7s) # # scaled_weight = defaultdict(int) # # for i in range(len(G.edges())): # scaled_weight[i] = defaultdict(int) # for u,v,d in G.edges(data=True): # scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s) values = range(256) jet = cm = plt.get_cmap('jet') cNorm = colors.Normalize(vmin=0, vmax=values[-1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) for u, v, d in G.edges(data=True): # lo = [] # la = [] # lo.append(subpref_coord[u][0]) # lo.append(subpref_coord[v][0]) # la.append(subpref_coord[u][1]) # la.append(subpref_coord[v][1]) # x, y = m(lo, la) # linewidth7s = scaled_weight[u][v] * 2.5 + 0.25 # m.plot(x,y, linewidth= linewidth7s) # if linewidth7s > 1: # print (linewidth7s) if d['weight'] >= 0: colorVal = scalarMap.to_rgba(values[v]) # linewidth7s = scaled_weight[u][v] * 2.5 + 0.35 # print u, v, d['weight'], scaled_weight[u][v] ########################################################################################################### ### no scaling vs scaling the width of the line ########################################################################################################### # linewidth7s = d['weight'] / 10 m.drawgreatcircle(subpref_coord[u][0], subpref_coord[u][1], \ subpref_coord[v][0], subpref_coord[v][1], linewidth= d['weight']*100, color=colorVal) # m.drawcoastlines() #m.fillcontinents() plt.savefig('/home/sscepano/Project7s/D4D/CI/commuting_centers/Igor/high_betweenes_routes4.png',dpi=700) #plt.show() ###################################################################################################3 return
cmap = plt.cm.spring for feature in neighborhoods["features"]: if feature["properties"]["neighborhood"].upper() in list(coop_hood_avgs.neighborhood): hood = feature["properties"]["neighborhood"].upper() value = coop_hood_avgs_trans[hood]["avg_gross"] color = cmap((value - vmin)/(vmax - vmin))[:3] else: color = "#666666" some_points = feature["geometry"]["coordinates"] lons, lats = np.array(some_points).T data = np.array(m(lons, lats)).T lines = LineCollection(data) lines.set_edgecolors("#333333") lines.set_facecolors(color) lines.set_linewidth(0.3) ax.add_collection(lines) ax1 = fig.add_axes([0.83, 0.05, 0.03, 0.92]) norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) cbar = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, orientation="vertical") cbar.set_label("Avg. Gross Co-op Rental Income per Sq. Ft ($)") dv = 5. cbar.set_ticks(np.arange(vmin, vmax+dv, dv)) cbar.ax.minorticks_on() plt.savefig("coop_rental_map.png") plt.show()
else: 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,)) #Now obtain the data in a given poly and assign a color to the value div = str(record[5]) #print record dval = divlookup(dfile,div,yyyy,int(mm)) #if(dval > valmax): dval = valmax - 0.1 lines.set_facecolors(cmap_temp([dval/cwidth])) lines.set_edgecolors(cmap_temp([dval/cwidth])) lines.set_linewidth(0.25) ax1.add_collection(lines) if(imgsize == 'GEO'): inProj = Proj(init='epsg:3338') outProj = Proj(init='epsg:4326') #Now read in the Alaska Climate Division Shapes and fill the basemap s = shapefile.Reader(r"./Shapefiles/AK_divisions_NAD83") shapes = s.shapes() records = s.records() for record, shape in zip(records,shapes): lons,lats = zip(*shape.points) lons,lats = transform(inProj,outProj,lons,lats)
def display_matrices(ax, grid, texture, scale=None, col=None): """Display on a matplotlib axis an ellipse representing a symmetric matrix at each grid element. Each axis of the ellipse corresponds to an eigenvalue and is oriented along its eigenvector. An axis corresponding to a positive eigenvalue is drawn. A 'coffee bean' has a negative eigenvalue smaller in absolute value than its positive eigenvalue. A 'capsule' has a negative eigenvalue larger in absolute value than its positive eigenvalue. A circle is when the two eigenvalues are equal in absolute value.""" XY = grid.mesh() mask = grid.mask() #convert the texture back to an array of matrices mat = tri2square(texture) #compute egenvalues and eigenvectors of texture for each cell of the grid evalues, evectors = np.linalg.eigh(mat) #width and height are the larger and smaller eigenvalues respectively ww = evalues[..., 1][mask] hh = evalues[..., 0][mask] #angle is given by the angle of the larger eigenvector aa = np.rad2deg(np.arctan2(evectors[..., 1, 1], evectors[..., 0, 1]))[mask] #sum of the eigenvalues (trace of the matrix) trace = ww + hh #np.where(np.abs(ww)>np.abs(hh), ww, hh)#ww*hh #color #if col is None: # if trace.ptp()>0: # col = plt.cm.viridis((trace.ravel() - trace.min())/trace.ptp()) # else: # col = plt.cm.viridis(np.ones_like(trace)) if scale is None: #scale = 1 ellipse_areas = np.pi * np.abs(np.prod(evalues, axis=-1)) rarea = ellipse_areas / grid.areas() scale = np.nanpercentile(np.sqrt(rarea[mask]), 90) if scale == 0: scale = np.nanmax(np.sqrt(rarea[mask])) if scale == 0: raise ValueError("All matrices are null") scale = 1 / scale #show ellipses ec = EllipseCollection( ww * scale, hh * scale, aa, units='xy', offsets=XY, transOffset=ax.transData, edgecolors=col, facecolors='none', ) #major and minor axes (only for positive eigenvalues) xyps = scale * np.transpose( evectors * np.maximum(0, evalues)[..., None, :], (0, 1, 3, 2))[mask].reshape(2 * len(ww), 2) * 0.5 ma = LineCollection([[-xyp, xyp] for xyp in xyps], offsets=np.repeat(XY, 2, axis=0), color=(0.5, 0.5, 0.5)) if col is None: if trace.ptp() > 0: ec.set_array(trace) ma.set_array(trace[mask.ravel()]) else: ec.set_edgecolors(col) ma.set_edgecolors(col) ax.add_collection(ec) ax.add_collection(ma) return ec
def map_commutes(G): import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import matplotlib as mpl mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. from shapelib import ShapeFile import dbflib from matplotlib.collections import LineCollection from matplotlib import cm ########################################################################################### fig = plt.figure(3) #Custom adjust of the subplots plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05) ax = plt.subplot(111) m = Basemap(projection='cyl',\ llcrnrlon=-9, \ llcrnrlat=3.8, \ urcrnrlon=-1.5, \ urcrnrlat = 11, \ resolution = 'h', \ # projection = 'tmerc', \ lat_0 = 7.38, \ lon_0 = -5.30) # read subpref coordinates subpref_coord = read_subpref_lonlat() shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE') for npoly in range(shp.info()[0]): shpsegs = [] shpinfo = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) # if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91: # raise ValueError,msg x, y = m(lons, lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) #print shapedict name = shapedict["ID_DEPART"] subpref_id = shapedict["ID_SP"] # add information about ring number to dictionary. shapedict['RINGNUM'] = ring+1 shapedict['SHAPENUM'] = npoly+1 shpinfo.append(shapedict) #print subpref_id #print name lines = LineCollection(shpsegs,antialiaseds=(1,)) # lines.set_facecolors(col[subpref_id]) lines.set_edgecolors('k') lines.set_linewidth(0.2) ax.add_collection(lines) if G.has_node(-1): G.remove_node(-1) if G.has_node(0): G.remove_node(0) max7s = 1 min7s = 10000000 for u,v,d in G.edges(data=True): if d['weight'] > max7s: max7s = d['weight'] if d['weight'] < min7s: min7s = d['weight'] max7s = float(max7s) print "max", (max7s) print "min", (min7s) scaled_weight = defaultdict(int) for i in range(256): scaled_weight[i] = defaultdict(int) for u,v,d in G.edges(data=True): scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s) for u, v, d in G.edges(data=True): # lo = [] # la = [] # lo.append(subpref_coord[u][0]) # lo.append(subpref_coord[v][0]) # la.append(subpref_coord[u][1]) # la.append(subpref_coord[v][1]) # x, y = m(lo, la) # linewidth7s = scaled_weight[u][v] * 2.5 + 0.25 # m.plot(x,y, linewidth= linewidth7s) # if linewidth7s > 1: # print (linewidth7s) linewidth7s = scaled_weight[u][v] * 2.5 + 0.25 m.drawgreatcircle(subpref_coord[u][0], subpref_coord[u][1], \ subpref_coord[v][0], subpref_coord[v][1], linewidth= linewidth7s, color='r') m.drawcoastlines() m.fillcontinents() plt.savefig('/home/sscepano/Project7s/D4D/CI/urban_rural/home_work/OUTPUT_files/maps/hw_commuting_cur.png',dpi=700) #plt.show() ###################################################################################################3 return
def make_country_map(countrylist, shapefilename, m, figname, year=None, bounds=(1, 2, 4, 6, 8, 10, 15, 20), cmap=cm.YlGnBu, logofile="../logos/logo_colloquium.png"): """ :param countrylist: list of country iso-codes :type countrylist: list :param shapefilename: path of the shape file :type shapefilename: str :param m: projection created with Basemap :param figname: path of the figure to be created :type figname: str :param year: considered year :type year: int :param bounds: bounds of the colorbar :param cmap: colormap :param logofile: file storing the CLQ logo :type logofile: str :return: """ # Count the occurrence of each country in the list countrycount = Counter(countrylist) nmax = max(countrycount.values()) shapes, records = read_shape(shapefilename) fig = plt.figure(figsize=(11.7, 8.3)) ax = plt.subplot(111) rcParams.update({'font.size': 16}) if year is not None: titletext = "{0}: {1} participants".format(year, len(countrylist)) plt.title(titletext, fontsize=20) m.drawcountries(linewidth=0.1) m.drawcoastlines(linewidth=0.1) """ axins = zoomed_inset_axes(ax, 2.5, loc=3) m.drawcountries(linewidth=.2, ax=axins) x, y = m(-15., 35.) x2, y2 = m(27, 60.) axins.set_xlim(x, x2) axins.set_ylim(y, y2) axins.axis('off') """ for record, shape in zip(records, shapes): countryname = record[1] if countryname in countrycount: lons, lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [ data, ] else: 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(cmap(countrycount[countryname] / nmax)) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) """ lines2 = LineCollection(segs, antialiaseds=(1,)) lines2.set_facecolors(cmap(countrycount[countryname] / nmax)) lines2.set_edgecolors('k') lines2.set_linewidth(0.1) axins.add_collection(lines2) """ cax = fig.add_axes([0.475, 0.21, 0.4, 0.02]) cmap.set_over((0., 0., 0.)) cb1 = colorbar.ColorbarBase(cax, cmap=cmap, norm=colors.BoundaryNorm(bounds, cmap.N), orientation='horizontal', spacing='uniform', extend='max', label='Number of participants') cb1.ax.xaxis.set_label_position('top') if os.path.exists(logofile): im = plt.imread(logofile) newax = fig.add_axes([0.85, 0.85, 0.07, 0.07], anchor='NE') newax.imshow(im) newax.axis('off') # Remove frame ax.axis('off') # Add year in upper-left corner # plt.annotate(year, xy=(0.05, 8.5), xycoords='axes fraction', fontsize=30) plt.savefig(figname, dpi=300, bbox_inches='tight') # plt.show() plt.close()