def plot(self, xys, neighborhoods=None, shpfile=None, outfile=None, title=None): if self.happy_ending: cm = get_cmap('RdBu') cm = get_cmap('Accent') f = plt.figure() ax = f.add_subplot(111) grid = ax.scatter(xys[:, 0], xys[:, 1], alpha=0.75, linewidths=0, \ s=80, marker=None, color='0.6', cmap=cm) axys = xys[self.agent_xyids, :] ax.scatter(axys[:, 0], axys[:, 1], alpha=0.8, linewidths=0, \ s=20, marker='o', c=self.group_map, cmap=cm) props = self.prop_groups + [1. - sum(self.prop_groups)] if title == None: title = "%i agents | %s share | %.2f similar wanted"\ %(self.pop_size, '_'.join(map(str, props)), \ self.pct_similar_wanted) plt.title(title, color='0.3') ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False) if neighborhoods: nr, nc = neighborhoods r = len(set(xys[:, 1])) ir = int(np.round((r * 1.) / nr)) nrb = [i + ir for i in range(-ir, r, ir)] nrb[-1] += 0.5 nrb[0] -= 0.5 c = len(set(xys[:, 0])) ic = int(np.round((c * 1.) / nc)) ncb = [i + ic for i in range(-ic, c, ic)] ncb[0] -= 0.5 ncb[-1] += 0.5 # Horizontal lines for i in nrb: plt.hlines(i - 0.5, xmin=-1, xmax=c, color='k') # Vertical lines for i in ncb: plt.vlines(i - 0.5, ymin=-1, ymax=r, color='k') elif shpfile: from pysal.contrib.viz import mapping as viz shp = ps.open(shpfile) patchco = viz.map_poly_shp(shp) patchco.set_facecolor('none') patchco.set_edgecolor('0.3') patchco.set_linewidth(0.3) ax = viz.setup_ax([patchco], ax) fc = '1' f.set_facecolor(fc) if not outfile: plt.show() else: plt.savefig(outfile, facecolor=fc) else: print 'No use in plotting a bad ending'
def plot(self, xys, neighborhoods=None, shpfile=None, outfile=None, title=None): if self.happy_ending: cm = get_cmap('RdBu') cm = get_cmap('Accent') f = plt.figure() ax = f.add_subplot(111) grid = ax.scatter(xys[:, 0], xys[:, 1], alpha=0.75, linewidths=0, \ s=80, marker=None, color='0.6', cmap=cm) axys = xys[self.agent_xyids, :] ax.scatter(axys[:, 0], axys[:, 1], alpha=0.8, linewidths=0, \ s=20, marker='o', c=self.group_map, cmap=cm) props = self.prop_groups + [1. - sum(self.prop_groups)] if title == None: title = "%i agents | %s share | %.2f similar wanted"\ %(self.pop_size, '_'.join(map(str, props)), \ self.pct_similar_wanted) plt.title(title, color='0.3') ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False) if neighborhoods: nr, nc = neighborhoods r = len(set(xys[:, 1])) ir = int(np.round((r*1.)/nr)) nrb = [i+ir for i in range(-ir, r, ir)] nrb[-1] += 0.5 nrb[0] -= 0.5 c = len(set(xys[:, 0])) ic = int(np.round((c*1.)/nc)) ncb = [i+ic for i in range(-ic, c, ic)] ncb[0] -= 0.5 ncb[-1] += 0.5 # Horizontal lines for i in nrb: plt.hlines(i-0.5, xmin=-1, xmax=c, color='k') # Vertical lines for i in ncb: plt.vlines(i-0.5, ymin=-1, ymax=r, color='k') elif shpfile: from pysal.contrib.viz import mapping as viz shp = ps.open(shpfile) patchco = viz.map_poly_shp(shp) patchco.set_facecolor('none') patchco.set_edgecolor('0.3') patchco.set_linewidth(0.3) ax = viz.setup_ax([patchco], ax) fc = '1' f.set_facecolor(fc) if not outfile: plt.show() else: plt.savefig(outfile, facecolor=fc) else: print 'No use in plotting a bad ending'
def lisa_mapa(variavel, shapefile, p_thres=0.05, **kws): w = ps.queen_from_shapefile(shapefile) lisa = ps.Moran_Local(variavel, w) fig = plt.figure(figsize=(9, 7)) shp = ps.open(shapefile) base = maps.map_poly_shp(shp) base = maps.base_lisa_cluster(base, lisa, p_thres=p_thres) base.set_edgecolor('1') base.set_linewidth(0.1) ax = maps.setup_ax([base], [shp.bbox]) boxes, labels = maps.lisa_legend_components(lisa, p_thres=p_thres) plt.legend(boxes, labels, fancybox=True, **kws) plt.show();
def lisa_mapa(variavel, shapefile, p_thres=0.05, **kws): w = ps.queen_from_shapefile(shapefile) lisa = ps.Moran_Local(variavel, w) fig = plt.figure(figsize=(9, 7)) shp = ps.open(shapefile) base = maps.map_poly_shp(shp) base = maps.base_lisa_cluster(base, lisa, p_thres=p_thres) base.set_edgecolor('1') base.set_linewidth(0.1) ax = maps.setup_ax([base], [shp.bbox]) boxes, labels = maps.lisa_legend_components(lisa, p_thres=p_thres) plt.legend(boxes, labels, fancybox=True, **kws) plt.show()
def visualize_adjacency_graph(mggg_graph, out_dir=None): ''' Visualize an adjacency graph Input: mggg_graph (Graph): A graph object from adjacency_graphs.algorithms out_dir (string, optional): Path to the output file. If none provided, no file will be created Output: fig (matplotlib.pyplot): An object which can be plotted ''' # open the file and obtain pysal geometries shp = mggg_graph.loaded_geodata # setting up matplot figure fig = plt.figure(figsize=(9, 9)) fig.set_facecolor('white') base = maps.map_poly_shp(shp) base.set_linewidth(0.75) base.set_facecolor('none') base.set_edgecolor('0.8') # Build a dictionary to associate geoid and index. data = mggg_graph.shape_df gti = {} for index, row in data.iterrows(): gti[row[mggg_graph.id_column]] = index # graph contains polygons matched to their neighbors, uses polygon identifiers graph = mggg_graph.neighbors # obtain the centroids of polygons polygon_centroids = {x: y.centroid for x, y in enumerate(shp)} # connect centroids of the polygons using LineCollection edge_list = [(polygon_centroids[gti[poly1]], polygon_centroids[gti[poly2]]) for poly1, neighbors in graph.items() for poly2 in neighbors] edge_list = LineCollection(edge_list) edge_list.set_linewidth(0.20) ax = maps.setup_ax([base, edge_list], [shp.bbox, shp.bbox]) fig.add_axes(ax) # save your output if (out_dir is not None): savefig(out_dir) return fig
def choropleth(shp, bbox, data, title=None): data = 1.0 * np.nan_to_num(np.array(data)) normed = (data - data.min()) / data.ptp() if np.min(data) < 0: cmap = 'PRGn' else: cmap = 'viridis' shapes = maps.map_poly_shp(shp) zips = maps.base_choropleth_classless(shapes, values=normed, cmap=cmap) zips.set_linewidth(0.75) zips.set_edgecolor('0.8') fig = plt.figure(figsize=(7, 7)) ax = maps.setup_ax([zips], [bbox]) fig.add_axes(ax) if title: plt.title(title) m = mpl.cm.ScalarMappable(cmap=cmap) m.set_array(np.unique(data)) plt.colorbar(m) plt.show()
def visualize_adjacency_graph(mggg_graph, fig=None, out_dir=None): """ visualize_adjacency_graph create and visualize an adjacency graph of geometries in an shp file. @param file_dir a string directory for the shp file which one wishes to analyze. @param out_dir a string directory where one wishes to save the output image. Image will not be saved if this is None. """ if not fig: fig = plt.figure(figsize=(9, 9)) fig.set_facecolor('white') base = maps.map_poly_shp(mggg_graph.loaded_geodata) base.set_linewidth(0.75) base.set_facecolor('none') base.set_edgecolor('0.8') # obtain the centroids of polygons polygon_centroids = { x: y.centroid for x, y in enumerate(mggg_graph.loaded_geodata) } # connect centroids of the polygons using LineCollection edge_list = ((polygon_centroids[poly1], polygon_centroids[poly2]) for poly1, neighbors in mggg_graph.neighbors.items() for poly2 in neighbors) edge_list = LineCollection(edge_list) edge_list.set_linewidth(0.20) ax = maps.setup_ax( [base, edge_list], [mggg_graph.loaded_geodata.bbox, mggg_graph.loaded_geodata.bbox]) fig.add_axes(ax) return fig
def visualize_adjacency_graph(mggg_graph, bokeh_graph=False, out_dir=None): ''' Visualize an adjacency graph Input: mggg_graph (Graph): A graph object from adjacency_graphs.algorithms out_dir (string, optional): Path to the output file. If none provided, no file will be created Output: fig (matplotlib.pyplot): An object which can be plotted ''' # open the file and obtain pysal geometries shp = mggg_graph.loaded_geodata # setting up matplot figure fig = plt.figure(figsize=(9, 9)) fig.set_facecolor('white') base = maps.map_poly_shp(shp) base.set_linewidth(0.75) base.set_facecolor('none') base.set_edgecolor('0.8') # Build a dictionary to associate geoid and index. data = mggg_graph.shape_df gti = {} for index, row in data.iterrows(): gti[row[mggg_graph.id_column]] = index # graph contains polygons matched to their neighbors, uses polygon identifiers graph = mggg_graph.neighbors # obtain the centroids of polygons polygon_centroids = {x: y.centroid for x, y in enumerate(shp)} if bokeh_graph == False: edge_list = [ (polygon_centroids[gti[poly1]], polygon_centroids[gti[poly2]]) for poly1, neighbors in graph.items() for poly2 in neighbors ] edge_list = LineCollection(edge_list) edge_list.set_linewidth(0.20) ax = maps.setup_ax([base, edge_list], [shp.bbox, shp.bbox]) fig.add_axes(ax) # save your output if (out_dir is not None): savefig(out_dir) return fig else: edge_list_bokeh_x = [[ polygon_centroids[gti[poly1]][0], polygon_centroids[gti[poly2]][0] ] for poly1, neighbors in graph.items() for poly2 in neighbors] edge_list_bokeh_y = [[ polygon_centroids[gti[poly1]][1], polygon_centroids[gti[poly2]][1] ] for poly1, neighbors in graph.items() for poly2 in neighbors] lons, lats = gpd_bokeh(mggg_graph.shape_df) source = ColumnDataSource( data=dict(x=lons, y=lats, name=mggg_graph.shape_df.NAME)) TOOLS = "pan, wheel_zoom, box_zoom, reset, hover, save" p = figure(title="Adjecency Graph", tools=TOOLS, plot_width=900, plot_height=900) p.patches('x', 'y', source=source, fill_alpha=0.7, color='white', line_color='black', line_width=0.5) hover = p.select_one(HoverTool) hover.point_policy = 'follow_mouse' hover.tooltips = [ ("Name", "@name"), ("(Long, Lat)", "($x, $y)"), ] p.multi_line(edge_list_bokeh_x, edge_list_bokeh_y, line_width=1) output_file("adjacency.html", title="Adjacency Graph") show(p)
import numpy as np import pysal as ps import random as rdm from pysal.contrib.viz import mapping as maps import matplotlib.pyplot as plt shp_link = 'transportation.shp' shp = ps.open(shp_link) fig = plt.figure() base = maps.map_poly_shp(shp) base.set_facecolor('none') base.set_linewidth(0.75) base.set_edgecolor('0.8') ax = maps.setup_ax([base]) fig.add_axes(ax) plt.show()
def plot_lisa(lisa, st, msa, outfile=None, thr=0.05, title=''): ''' Plot LISA results for MSAs on background map of US states NOTE: shapefiles hardcoded linked to paths inside the function ... Arguments --------- lisa : Moran_Local LISA object from PySAL st : str Path to states shape msa : str Path to MSA points shape outfile : str [Optional] Path to png to be written thr : float [Optional] Significance value to identify clusters title : str [Optional] Title for the figure title : str Returns ------- None ''' sig = (lisa.p_sim < thr) * 1 vals = pd.Series(lisa.q * sig) states = ps.open(st) pts = ps.open(msa) fig = plt.figure(figsize=(9, 5)) base = maps.map_poly_shp(states) base.set_facecolor('0.85') base.set_linewidth(0.75) base.set_edgecolor('0.95') msas = pd.np.array([pt for pt in ps.open(msa)]) sizes = vals.apply(lambda x: 4 if x==0 else 50) colors = vals.map(q_mapper) colors = pd.np.array(list(colors)) pts = [] for clas in q_mapper: i = vals[vals==clas].index p = plt.scatter(msas[i, 0], msas[i, 1], s=sizes[i], \ c=colors[i, :], label=q_names[clas]) p.set_linewidth(0) pts.append(p) plt.legend(loc=3, ncol=2, fontsize=14, scatterpoints=1, frameon=False) ax = maps.setup_ax([base] + pts) #ax = maps.setup_ax(pts) fig.add_axes(ax) if title: plt.title(title) if outfile: plt.savefig(outfile) else: plt.show() return None