def plot_flow(od_matrix, title, chengdu): colors = [cm.Spectral_r(x) for x in linspace(0, 1, 5)] df = od_matrix.copy() df_class = mpc.NaturalBreaks(df['ridership']) df['class'] = df_class.yb bins = df_class.bins fig, ax = plt.subplots(1, 1, figsize=(5, 5)) chengdu.plot(figsize=(5, 5), facecolor='none', edgecolor='black', linewidth=0.6, ax=ax, alpha=1) for i in range(len(bins)): sub = df[df['class'] == i] for j in sub.index: ax.annotate('', xy=(sub.loc[j, 'ori_x'], sub.loc[j, 'ori_y']), xytext=(sub.loc[j, 'end_x'], sub.loc[j, 'end_y']), arrowprops=dict(arrowstyle="->", color=colors[i], linewidth=0.5, alpha=0.8, shrinkA=0, shrinkB=0, patchA=None, patchB=None, connectionstyle='arc3,rad=-0.3')) ax.set_title(title, fontsize=16) ax.set_xlim(103.89, 104.24) ax.set_ylim(30.54, 30.8) line1, _ = ax.plot(((0, 0), (1, 1)), color=colors[0], alpha=0.8) line2, _ = ax.plot(((0, 0), (1, 1)), color=colors[1], alpha=0.8) line3, _ = ax.plot(((0, 0), (1, 1)), color=colors[2], alpha=0.8) line4, _ = ax.plot(((0, 0), (1, 1)), color=colors[3], alpha=0.8) line5, _ = ax.plot(((0, 0), (1, 1)), color=colors[4], alpha=1) plt.legend((line1, line2, line3, line4, line5), [ '{} - {}'.format(0.0, round(bins[0], 1)), '{} - {}'.format( round(bins[0], 1), round(bins[1], 1)), '{} - {}'.format( round(bins[1], 1), round(bins[2], 1)), '{} - {}'.format( round(bins[2], 1), round(bins[3], 1)), '{} - {}'.format( round(bins[3], 1), round(bins[4], 1)) ], framealpha=1, title='Trips', facecolor='whitesmoke') plt.xticks([]) plt.yticks([]) # plt.savefig(name, dpi=300, transparent=True, pad_inches=0) # plt.close(fig=fig) plt.show()
def add_coa(option): #Get Bounds x0, x1 = ax.get_xlim() y0, y1 = ax.get_ylim() #Plot COA gplt.choropleth(coas, ax=ax, projection=geoplot.crs.WebMercator(), hue=option, zorder=1, alpha=0.7, scheme=mc.NaturalBreaks(coas[option], k=5), cmap=option, legend=False, edgecolor='lightgray') #Set Extent ax.set_xlim(left=x0, right=x1) ax.set_ylim(bottom=y0, top=y1)
def add_legend(option): #Decide Format if option == 'SimpleCO2': frmt = '{:.1f}' else: frmt = '{:.0f}' #Legend Labels classification = mc.NaturalBreaks(coas[option], k=5) legend_labels = [] for i, c in enumerate(classification.counts): if i == 0: str_ = "{0} - {1}".format(str(frmt.format(coas[option].min())), str(frmt.format(classification.bins[i]))) else: str_ = "{0} - {1}".format( str(frmt.format(classification.bins[i - 1])), str(frmt.format(classification.bins[i]))) str_ += "({0})".format(c) legend_labels.append(str_) #Legend Handles cmap = matplotlib.cm.get_cmap(option) handles = [ Patch(edgecolor='black', facecolor=cmap(0.)), Patch(edgecolor='black', facecolor=cmap(.25)), Patch(edgecolor='black', facecolor=cmap(.5)), Patch(edgecolor='black', facecolor=cmap(.75)), Patch(edgecolor='black', facecolor=cmap(1.)) ] #Create Legend legend = ax.legend(handles=handles, labels=legend_labels, loc='upper left', title=get_title(option), framealpha=1, facecolor='white', edgecolor='black', fancybox=False, handlelength=1) legend._legend_box.align = 'left' #align text #Make Draggable legend.set_draggable(True, update='loc')
import numpy as np import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt import matplotlib.colors import mapclassify # get coefficient surface w_sh legend_classes = mapclassify.NaturalBreaks( gwr_map_2.loc[(~gwr_map_2['w_sh'].isna()), 'w_sh'], k=5) legend_classes = mapclassify.UserDefined( gwr_map_2.loc[(~gwr_map_2['w_sh'].isna()), 'w_sh'], bins=[-5.55, 0, 5.64, 8.93, 12.69]) mapping = dict([(i, s) for i, s in enumerate(legend_classes.get_legend_classes())]) # plot fig = plt.figure(figsize=(10, 8)) ax = fig.add_axes([0, 0, 0.95, 0.95]) gwr_map_2.loc[(~gwr_map_2['w_sh'].isna())].assign(cl = legend_classes.yb).plot(column = 'cl', categorical = True,\ k = 6, cmap = 'coolwarm', norm = matplotlib.colors.Normalize(-1.8,3.5),\ linewidth = 0.3,\ alpha = 0.7,\ ax = ax, edgecolor = 'black', legend = True,\ legend_kwds = {'loc':'lower left',\ 'fontsize': 10,\ 'frameon': False,\ 'title': 'GWR coefficients\nw_sh\n',\ 'title_fontsize': 12,\ 'edgecolor': 'gray'})
import matplotlib.pyplot as plt import geopandas import equal_area_breaks import mapclassify from demo_utils import * world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) world = world[(world.pop_est > 0) & (world.name != "Antarctica")] world['gdp_per_cap'] = 1000000 * (world.gdp_md_est / world.pop_est) world = world.to_crs({'proj': 'wintri'}) world['area'] = world.geometry.area data_col = 'gdp_per_cap' cmap = cmap_yl_or_rd() fig, axes = plt.subplots(nrows=2, ncols=2) plot_classes(world, mapclassify.Quantiles(world[data_col]), fig, axes[0, 0], cmap) plot_classes(world, mapclassify.EqualInterval(world[data_col]), fig, axes[1, 0], cmap) plot_classes(world, mapclassify.NaturalBreaks(world[data_col]), fig, axes[0, 1], cmap) plot_classes( world, equal_area_breaks.Equal_Area_DP(world[data_col], area=world['area']), fig, axes[1, 1], cmap) plt.show()
def test_classify(): # data link_to_data = examples.get_path('columbus.shp') gdf = gpd.read_file(link_to_data) x = gdf['HOVAL'].values # box_plot a = classify(x, 'box_plot') b = mapclassify.BoxPlot(x) _assertions(a, b) # EqualInterval a = classify(x, "EqualInterval", k=3) b = mapclassify.EqualInterval(x, k=3) _assertions(a, b) # FisherJenks a = classify(x, "FisherJenks", k=3) b = mapclassify.FisherJenks(x, k=3) _assertions(a, b) a= classify(x, "FisherJenksSampled", k=3, pct_sampled=0.5, truncate=False) b = mapclassify.FisherJenksSampled(x, k=3, pct=0.5,truncate=False) _assertions(a, b) # headtail_breaks a = classify(x, 'headtail_breaks') b = mapclassify.HeadTailBreaks(x) _assertions(a, b) # quantiles a = classify(x, 'quantiles',k=3) b = mapclassify.Quantiles(x, k=3) _assertions(a, b) # percentiles a = classify(x, 'percentiles', pct=[25,50,75,100]) b = mapclassify.Percentiles(x, pct=[25,50,75,100]) _assertions(a, b) #JenksCaspall a = classify(x, 'JenksCaspall', k=3) b = mapclassify.JenksCaspall(x, k=3) _assertions(a, b) a = classify(x, 'JenksCaspallForced', k=3) b = mapclassify.JenksCaspallForced(x, k=3) _assertions(a, b) a = classify(x, 'JenksCaspallSampled', pct_sampled=0.5) b = mapclassify.JenksCaspallSampled(x, pct=0.5) _assertions(a, b) # natural_breaks, max_p_classifier a = classify(x, 'natural_breaks') b = mapclassify.NaturalBreaks(x) _assertions(a, b) a = classify(x, 'max_p', k=3, initial=50) b = mapclassify.MaxP(x, k=3, initial=50) _assertions(a, b) # std_mean a = classify(x, 'std_mean', multiples=[-1,-0.5,0.5,1]) b = mapclassify.StdMean(x, multiples=[-1,-0.5,0.5,1]) _assertions(a, b) # user_defined a = classify(x, 'user_defined', bins=[20, max(x)]) b = mapclassify.UserDefined(x, bins=[20, max(x)]) _assertions(a, b)