### Install mapclassify from source Source: https://github.com/pysal/mapclassify/blob/main/docs/installation.md Install the package from a local directory containing the source distribution. ```default pip install . ``` -------------------------------- ### Load example data and create quantiles Source: https://github.com/pysal/mapclassify/blob/main/notebooks/02_legends.ipynb Load the default example dataset and initialize a Quantiles classifier with 6 classes. ```python cal = mapclassify.load_example() ``` ```python q6 = mapclassify.Quantiles(cal, k=6) q6 ``` -------------------------------- ### Install mapclassify development version Source: https://github.com/pysal/mapclassify/blob/main/docs/installation.md Install the latest development version directly from the GitHub repository. ```default pip install git+https://github.com/pysal/mapclassify.git ``` -------------------------------- ### Local development installation Source: https://github.com/pysal/mapclassify/blob/main/README.md Commands to set up a local development environment for mapclassify. ```bash conda-env create -f environment.yml conda activate mapclassify conda remove -n mapclassify mapclassify pip install -e . ``` -------------------------------- ### Import Mapclassify and Get Version Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Imports the mapclassify library and displays its current version. Ensure mapclassify is installed. ```python import numpy import mapclassify mapclassify.__version__ ``` -------------------------------- ### Initialize mapclassify Source: https://github.com/pysal/mapclassify/blob/main/notebooks/06_api.ipynb Import necessary libraries and check the installed version of mapclassify. ```python import geopandas import libpysal import mapclassify ``` ```python mapclassify.__version__ ``` -------------------------------- ### Load Example Data Source: https://github.com/pysal/mapclassify/blob/main/README.md Load the built-in employment density dataset for California counties. ```python >>> import mapclassify >>> y = mapclassify.load_example() >>> y.mean() 125.92810344827588 >>> y.min(), y.max() (0.13, 4111.4499999999998) ``` -------------------------------- ### Load example dataset Source: https://github.com/pysal/mapclassify/blob/main/notebooks/01_maximum_breaks.ipynb Load the built-in California employment density dataset. ```python y = mc.load_example() ``` -------------------------------- ### Import necessary libraries Source: https://github.com/pysal/mapclassify/blob/main/notebooks/09_legendgram.ipynb Import geopandas, examples from libpysal, and mapclassify. ```python import geopandas as gpd from libpysal import examples import mapclassify ``` -------------------------------- ### Load example dataset Source: https://github.com/pysal/mapclassify/blob/main/notebooks/06_api.ipynb Load the Columbus dataset using libpysal and prepare the target variable. ```python pth = libpysal.examples.get_path("columbus.shp") gdf = geopandas.read_file(pth) y = gdf.HOVAL gdf.head() ``` -------------------------------- ### Install mapclassify via pip Source: https://github.com/pysal/mapclassify/blob/main/docs/installation.md Install the latest released version of mapclassify from the Python Package Index. ```default pip install -U mapclassify ``` -------------------------------- ### Import Libraries and Get Mapclassify Version Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Imports necessary libraries for geospatial data handling and visualization, and checks the installed version of mapclassify. ```python import geopandas import libpysal import matplotlib.pyplot as plt import mapclassify mapclassify.__version__ ``` -------------------------------- ### Install mapclassify via conda Source: https://github.com/pysal/mapclassify/blob/main/docs/installation.md Use the conda-forge channel to install the released version of mapclassify. ```default conda install -c conda-forge mapclassify ``` -------------------------------- ### Check mapclassify version Source: https://github.com/pysal/mapclassify/blob/main/notebooks/02_legends.ipynb Verify the installed version of the mapclassify library. ```python import mapclassify mapclassify.__version__ ``` -------------------------------- ### Example: MaximumBreaks Classifier Usage Source: https://github.com/pysal/mapclassify/blob/main/notebooks/01_maximum_breaks.ipynb Demonstrates the basic usage of the MaximumBreaks classifier, including initialization with data and specifying the number of classes. Shows how to access the number of classes and the calculated bins. ```python import mapclassify cal = mapclassify.load_example() mb = mapclassify.MaximumBreaks(cal, k=5) mb.k mb.bins mb.counts.tolist() ``` -------------------------------- ### Import Libraries and Load Data Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Imports necessary libraries and loads a geospatial dataset. Ensure geopandas and geodatasets are installed. ```python import geodatasets import geopandas as gpd import pandas as pd import mapclassify from mapclassify.util import get_color_array %load_ext watermark %watermark -a 'eli knaap' -iv ``` ```python df = gpd.read_file(geodatasets.get_path("geoda cincinnati")).to_crs(4326) ``` -------------------------------- ### Setup GeoPandas and Seaborn Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Imports necessary libraries, GeoPandas for geospatial data handling and Seaborn for enhanced plotting. Seaborn's default style is applied. ```python import geopandas import seaborn seaborn.set() ``` -------------------------------- ### Mapclassify Classifiers Source: https://github.com/pysal/mapclassify/blob/main/notebooks/01_maximum_breaks.ipynb Lists all available classifiers in the mapclassify library and provides an example of how to access the MaximumBreaks classifier's documentation. ```APIDOC ## Available Classifiers This section lists all the classification algorithms available within the `mapclassify` library. ### Method GET ### Endpoint /pysal/mapclassify/classifiers ### Description Retrieves a list of all available classifier names. ### Response Example ```json { "classifiers": [ "BoxPlot", "EqualInterval", "FisherJenks", "FisherJenksSampled", "HeadTailBreaks", "JenksCaspall", "JenksCaspallForced", "JenksCaspallSampled", "MaxP", "MaximumBreaks", "NaturalBreaks", "Quantiles", "Percentiles", "PrettyBreaks", "StdMean", "UserDefined" ] } ``` ## Introspecting a Classifier (MaximumBreaks Example) This section demonstrates how to get detailed information about a specific classifier, using `MaximumBreaks` as an example. ### Method GET ### Endpoint /pysal/mapclassify/classifiers/MaximumBreaks ### Description Provides detailed documentation for the `MaximumBreaks` classifier, including its signature, parameters, attributes, and examples. ### Parameters #### Query Parameters - **y** (numpy.array) - Required - Values to classify. - **k** (int) - Optional - The number of classes required. Defaults to 5. - **mindiff** (float) - Optional - The minimum difference between class breaks. Defaults to 0. ### Response Example (Success Response - 200) ```json { "classifier": "MaximumBreaks", "init_signature": "mc.MaximumBreaks(y, k=5, mindiff=0)", "docstring": "Maximum Breaks Map Classification.", "parameters": [ {"name": "y", "type": "numpy.array", "required": true, "description": "values to classify.", "shape": "(n,1)"}, {"name": "k", "type": "int", "required": false, "description": "The number of classes required.", "default": 5}, {"name": "mindiff", "type": "float", "required": false, "description": "The minimum difference between class breaks.", "default": 0} ], "attributes": [ {"name": "yb", "type": "numpy.array", "description": "bin IDs for observations.", "shape": "(n,1)"}, {"name": "bins", "type": "numpy.array", "description": "the upper bounds of each class.", "shape": "(k,1)"}, {"name": "k", "type": "int", "description": "The number of classes.", "default": 5}, {"name": "counts", "type": "numpy.array", "description": "the number of observations falling in each class.", "shape": "(k,1)"} ], "examples": [ "import mapclassify", "cal = mapclassify.load_example()", "mb = mapclassify.MaximumBreaks(cal, k=5)", "mb.k", "mb.bins", "mb.counts.tolist()" ] } ``` ``` -------------------------------- ### Explain and Load Geospatial Data Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Uses libpysal to get information about a sample dataset ('sids2') and then loads the corresponding shapefile into a GeoDataFrame using geopandas. ```python libpysal.examples.explain("sids2") ``` ```python pth = libpysal.examples.get_path("sids2.shp") gdf = geopandas.read_file(pth) gdf.head() ``` -------------------------------- ### Retrieve legend classes Source: https://github.com/pysal/mapclassify/blob/main/notebooks/02_legends.ipynb Get legend labels as a list of strings, optionally applying a custom format string. ```python q6.get_legend_classes() ``` ```python q6.get_legend_classes(fmt="{:.0f}") ``` -------------------------------- ### Percentiles Classifier with Default Cutoffs Source: https://context7.com/pysal/mapclassify/llms.txt Applies the Percentiles classifier with default percentile cutoffs (1, 10, 50, 90, 99, 100) to example data. ```python import mapclassify y = mapclassify.load_example() # Default percentiles p = mapclassify.Percentiles(y) print(p) ``` -------------------------------- ### Plot choropleth with custom legend Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Example of plotting a GeoDataFrame with a specific classification and updating the legend labels. ```python ax = gdf.assign(cl=q10.yb).plot( figsize=(16, 9), column="cl", categorical=True, k=10, cmap="OrRd", linewidth=0.1, edgecolor="white", legend=True, legend_kwds={"loc": "lower right"}, ) ax.set_axis_off() replace_legend_items(ax.get_legend(), mapping) ``` -------------------------------- ### Percentiles Classifier with Custom Cutoffs Source: https://context7.com/pysal/mapclassify/llms.txt Applies the Percentiles classifier with custom percentile cutoffs (tertiles: 33, 66, 100) to example data. ```python import mapclassify y = mapclassify.load_example() # Custom percentiles (tertiles) p3 = mapclassify.Percentiles(y, pct=[33, 66, 100]) print(p3) print(f"Tercile boundaries: {p3.bins}") ``` -------------------------------- ### Get Legend Class Intervals Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Retrieves a list of strings representing the class intervals used by the Quantiles classifier, suitable for creating a legend. ```python q10.get_legend_classes() ``` -------------------------------- ### Configure widget bindings Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Setting up dropdown options for classes and colormaps based on the selected data type. ```python bindings = { "Sequential": range(3, 9 + 1), "Diverging": range(3, 11 + 1), "Qualitative": range(3, 12 + 1), } cmap_bindings = { "Sequential": list(sequential.keys()), "Diverging": list(diverging.keys()), "Qualitative": list(qualitative.keys()), } class_val = Dropdown(options=bindings[data_type.value], value=5) cmap_val = Dropdown(options=cmap_bindings[data_type.value]) ``` -------------------------------- ### Initialize colorbrewer maps Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Extracting color map dictionaries from the colorbrewer library. ```python sequential = colorbrewer.COLOR_MAPS["Sequential"] diverging = colorbrewer.COLOR_MAPS["Diverging"] qualitative = colorbrewer.COLOR_MAPS["Qualitative"] ``` -------------------------------- ### Set up classification parameters Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Defines a dictionary 'params' to hold different classification methods ('rook', 'queen', 'geos', 'dist1') and their associated keyword arguments for the greedy algorithm. ```python params = { "rook": {"sw": "rook"}, "queen": {"sw": "queen"}, "geos": {"min_distance": 0}, "dist1": {"min_distance": 1}, } ``` -------------------------------- ### Initialize interactive display Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Binding observers to widgets and displaying the interactive interface. ```python data_type.observe(type_change, names=["value"]) cmap_val.observe(cmap_change, names=["value"]) out = Output() Tab().children = [out] interact(update_map, method=list(k_classifiers.keys()), cmap=cmap_val, k=class_val) display(VBox([data_type, out])) ``` -------------------------------- ### Initialize Lattice GeoDataFrame Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Create a 10x10 polygon lattice. ```python gdf = poly_lattice_gdf(10, plot=True) ``` -------------------------------- ### Importing Lonboard Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Import necessary classes for lonboard visualization. ```python from lonboard import Map, PolygonLayer ``` -------------------------------- ### Creating and using a classification instance Source: https://github.com/pysal/mapclassify/blob/main/README.md Instantiate a classifier to access bins, counts, and assigned bin indices. ```python >>> bp = mapclassify.BoxPlot(y) >>> bp >>> bp.bins >>> bp.counts >>> bp.yb ``` -------------------------------- ### Applying Classification Schemes Source: https://github.com/pysal/mapclassify/blob/main/notebooks/value_by_alpha.ipynb Demonstrating various classification methods like quantiles, natural breaks, and Fisher Jenks for binning data. ```python # Create new figure fig, axs = plt.subplots(2, 2, figsize=(15, 10)) # classify with Quantiles axs[0, 0].set_axis_off() vba_choropleth( x, y, gdf, cmap="viridis", ax=axs[0, 0], x_classification_kwds={"classifier": "quantiles", "k": 3}, y_classification_kwds={"classifier": "quantiles", "k": 3}, ) # classifier with Natural Breaks axs[0, 1].set_axis_off() vba_choropleth( x, y, gdf, cmap="viridis", ax=axs[0, 1], x_classification_kwds={"classifier": "natural_breaks"}, y_classification_kwds={"classifier": "natural_breaks"}, ) # classify with Standard Deviation Mean axs[1, 0].set_axis_off() vba_choropleth( x, y, gdf, cmap="viridis", ax=axs[1, 0], x_classification_kwds={"classifier": "std_mean"}, y_classification_kwds={"classifier": "std_mean"}, ) # classify with Fisher Jenks axs[1, 1].set_axis_off() vba_choropleth( x, y, gdf, cmap="viridis", ax=axs[1, 1], x_classification_kwds={"classifier": "fisher_jenks", "k": 3}, y_classification_kwds={"classifier": "fisher_jenks", "k": 3}, ) plt.show() ``` -------------------------------- ### Importing Dependencies Source: https://github.com/pysal/mapclassify/blob/main/notebooks/value_by_alpha.ipynb Required libraries for data handling and visualization. ```python import geopandas import libpysal import matplotlib.pyplot as plt ``` -------------------------------- ### Get Counts for Global Classifier Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Retrieves the counts for the global classifier when using pooled classification with k=4. This provides the overall distribution across all pooled intervals. ```python res.global_classifier.counts ``` -------------------------------- ### Import interactive widgets and color palettes Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Required imports for building the interactive exploration application. ```python from ipywidgets import ( Button, Dropdown, FloatSlider, HBox, IntSlider, Label, Output, RadioButtons, Tab, VBox, interact, ) from palettable import colorbrewer ``` -------------------------------- ### Get Bins for First Column BoxPlot Classifier Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Retrieves the bin edges for the first column's pooled 'BoxPlot' classifier. This shows the specific interval boundaries determined by the BoxPlot method. ```python res.col_classifiers[0].bins ``` -------------------------------- ### Get Class Assignments for First Column BoxPlot Classifier Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Retrieves the class assignments (yb) for the first column's pooled 'BoxPlot' classifier. This indicates which interval each observation in the first column belongs to. ```python c0, c1, c2 = res.col_classifiers c0.yb ``` -------------------------------- ### Preparing Data for Mapping Source: https://github.com/pysal/mapclassify/blob/main/notebooks/value_by_alpha.ipynb Loading the Columbus neighborhood dataset and defining variables for the choropleth. ```python link_to_data = libpysal.examples.get_path("columbus.shp") gdf = geopandas.read_file(link_to_data) gdf.columns ``` ```python x = "HOVAL" y = "CRIME" ``` -------------------------------- ### Import Libraries Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Imports necessary libraries for spatial analysis and warnings management. ```python import warnings import libpysal ``` -------------------------------- ### Get Counts for Last Column Classifier Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Retrieves the counts for the last column's classifier when using pooled classification with k=4. This shows the data distribution within the last column's intervals. ```python res.col_classifiers[-1].counts ``` -------------------------------- ### Render Deck with GeoJsonLayer Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Configure a Pydeck Deck object using a GeoJsonLayer and a defined ViewState. ```python layers = [ pdk.Layer( "GeoJsonLayer", data=df.to_crs(4326)[["geometry", "fill"]], get_fill_color="fill", auto_highlight=True, pickable=True, ), ] view_state = pdk.ViewState( **{ "latitude": df.union_all().centroid.y, "longitude": df.union_all().centroid.x, "zoom": 12, } ) D = pdk.Deck( layers, map_provider="carto", map_style=pdk.map_styles.LIGHT, initial_view_state=view_state, ) D ``` -------------------------------- ### Get Counts for First Column Classifier Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Retrieves the counts for the first column's classifier when using pooled classification with k=4. This helps in understanding the distribution of data within the first column's assigned intervals. ```python res.col_classifiers[0].counts ``` -------------------------------- ### Instantiate a Quantiles Classifier Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Creates a mapclassify Quantiles classifier object for the 'SIDR79' data with 10 classes. This allows for inspection of the classification intervals and counts. ```python q10 = mapclassify.Quantiles(gdf.SIDR79, k=10) q10 ``` -------------------------------- ### Run and Compare Greedy Strategies Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Iterates through different greedy strategies, measures their execution time and number of colors, and stores the results. It includes a warning filter for geographic CRS issues. ```python times = {} with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message="Geometry is in a geographic CRS.", category=UserWarning ) for strategy in strategies: if strategy == "balanced": for mode in balanced_modes: stgy_mode = strategy + "_" + mode print(stgy_mode) kwargs = {"strategy": strategy, "balance": mode, "sw": sw} mean_time, colors = run_greedy(world, kwargs, runs=20) printer("time", mean_time, numpy.max(colors)) world[stgy_mode], times[stgy_mode] = colors, mean_time else: print(strategy) kwargs = {"strategy": strategy, "sw": sw} mean_time, colors = run_greedy(world, kwargs, runs=20) printer("time", mean_time, numpy.max(colors)) world[strategy], times[strategy] = colors, mean_time ``` -------------------------------- ### Load and prepare GeoDataFrame Source: https://github.com/pysal/mapclassify/blob/main/notebooks/09_legendgram.ipynb Load a shapefile into a GeoDataFrame and reproject it to EPSG:5070. Displays the head of the GeoDataFrame. ```python gdf = gpd.read_file(examples.get_path("NAT.shp")).to_crs(epsg=5070) gdf.head() ``` -------------------------------- ### Greedy Topological Coloring (Default) Source: https://context7.com/pysal/mapclassify/llms.txt Performs greedy topological coloring on African map data using default settings (balanced by count) and prints the number of unique colors used and their counts. ```python from mapclassify import greedy import geopandas as gpd # Load geographic data world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[world.continent == 'Africa'].copy() africa = africa.to_crs('ESRI:102022') # Projected CRS for Africa # Default balanced coloring (by count) africa['color'] = greedy(africa) print(f"Colors used: {africa['color'].nunique()}") print(africa['color'].value_counts()) ``` -------------------------------- ### Handle UserWarnings in Classification Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Demonstrates how to catch and handle UserWarnings, specifically when a classification method like MaximumBreaks encounters insufficient unique differences in the data. It shows how to ignore warnings after catching them. ```python import warnings with warnings.catch_warnings(): warnings.filterwarnings("error") try: mapclassify.MaximumBreaks(c0.y, k=5) except UserWarning as e: print(e) with warnings.catch_warnings(): warnings.filterwarnings("ignore") mapclassify.MaximumBreaks(c0.y, k=5) ``` -------------------------------- ### Inspect dataset bounds Source: https://github.com/pysal/mapclassify/blob/main/notebooks/01_maximum_breaks.ipynb Retrieve the minimum and maximum values of the dataset. ```python y.min() ``` ```python y.max() ``` -------------------------------- ### Import Shapely Point Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Required import for generating point geometries. ```python from shapely.geometry import Point ``` -------------------------------- ### Plot performance of rook and queen methods Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Creates a line plot specifically comparing the performance of the 'rook' and 'queen' classification methods. This plot helps to visualize the minimal performance difference between these two methods. ```python ax = times.loc[["rook", "queen"]].T.plot() ax.set_ylabel("time (s)") ax.set_xlabel("# of polygons") locs, labels = plt.xticks() plt.xticks(ticks=locs, labels=(times.columns**2)[:7], rotation="vertical"); ``` -------------------------------- ### Import necessary libraries for performance testing Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Imports the 'time', 'numpy', and 'pandas' libraries required for timing operations and data manipulation in the performance tests. ```python import time import numpy import pandas ``` -------------------------------- ### Greedy Topological Coloring (Largest First Strategy) Source: https://context7.com/pysal/mapclassify/llms.txt Performs greedy topological coloring on African map data using the Largest First strategy. ```python from mapclassify import greedy import geopandas as gpd # Load geographic data world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[world.continent == 'Africa'].copy() africa = africa.to_crs('ESRI:102022') # Projected CRS for Africa # Use NetworkX strategies africa['color_largest'] = greedy(africa, strategy='largest_first') ``` -------------------------------- ### Import Matplotlib for plotting Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Imports the 'matplotlib.pyplot' library, commonly aliased as 'plt', for creating visualizations of the performance data. ```python import matplotlib.pyplot as plt ``` -------------------------------- ### Displaying Color Array Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Inspect the generated color array. ```python colors ``` -------------------------------- ### Initialize PolygonLayer with Pydeck Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Create a map layer using PolygonLayer from a GeoPandas DataFrame. ```python layer = PolygonLayer.from_geopandas( df, get_fill_color=colors, ) m = Map(layers=[layer], _height=800) m ``` -------------------------------- ### Use original API Source: https://github.com/pysal/mapclassify/blob/main/notebooks/06_api.ipynb Perform classification using the original class-based API. ```python bp = mapclassify.BoxPlot(y) bp ``` -------------------------------- ### Generating Color Arrays for Lonboard Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Create a 2D array of integers for lonboard using mapclassify schemes. ```python colors = get_color_array( df.DENSITY.values, scheme="quantiles", cmap="YlOrBr", alpha=0.6 ) ``` -------------------------------- ### Binning new data Source: https://github.com/pysal/mapclassify/blob/main/README.md Use an existing classifier instance to find bins for new data points without recalibrating. ```python >>> bp = mapclassify.BoxPlot(y) >>> bp >>> bp.find_bin([0, 7, 3000, 48]) >>> bp ``` -------------------------------- ### Greedy coloring with 'largest_first' networkx strategy Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Applies the 'largest_first' coloring strategy from the networkx library via mapclassify.greedy. The output is visualized with a 'Set3' colormap. ```python africa["greedy_largest_first"] = greedy(africa, strategy="largest_first") ax = africa.plot( "greedy_largest_first", categorical=True, figsize=(8, 12), cmap="Set3", legend=True, edgecolor="w", ) ax.set_axis_off() ``` -------------------------------- ### Display benchmark results in a DataFrame Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Prints the 'times' DataFrame, which contains the benchmark results, showing the execution time for each classification method across different numbers of polygons. ```python times ``` -------------------------------- ### Create Spatial Weights Matrix Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Generates a Queen contiguity spatial weights matrix from a GeoDataFrame. ```python sw = libpysal.weights.Queen.from_dataframe( world, ids=world.index.to_list(), silence_warnings=True ) ``` -------------------------------- ### Configure classifier with different class counts Source: https://github.com/pysal/mapclassify/blob/main/notebooks/01_maximum_breaks.ipynb Apply the MaximumBreaks classifier with a different number of classes and inspect the resulting attributes. ```python mb7 = mc.MaximumBreaks(y, k=7) mb7 ``` ```python mb7.bins ``` ```python mb7.counts ``` ```python mb7.yb ``` -------------------------------- ### Robustness of scheme argument Source: https://github.com/pysal/mapclassify/blob/main/notebooks/06_api.ipynb Demonstrate case-insensitive and flexible string matching for classification schemes. ```python mapclassify.classify(y, "boxPlot") ``` ```python mapclassify.classify(y, "Boxplot") ``` ```python mapclassify.classify(y, "Box_plot") ``` -------------------------------- ### Calculate descriptive statistics Source: https://github.com/pysal/mapclassify/blob/main/notebooks/06_api.ipynb Compute mean, standard deviation, minimum, and maximum values for the dataset. ```python y.mean(), y.std(), y.min(), y.max() ``` -------------------------------- ### Interactive Exploration with Geopandas Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Use the explore method with a list of colors and specific map tiles. ```python df.explore(color=list(colors), tiles="CartoDB Positron") ``` -------------------------------- ### Greedy Topological Coloring (DSATUR Strategy) Source: https://context7.com/pysal/mapclassify/llms.txt Performs greedy topological coloring on African map data using the DSATUR strategy. ```python from mapclassify import greedy import geopandas as gpd # Load geographic data world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[world.continent == 'Africa'].copy() africa = africa.to_crs('ESRI:102022') # Projected CRS for Africa # Use NetworkX strategies africa['color_dsatur'] = greedy(africa, strategy='DSATUR') ``` -------------------------------- ### Create a Basic Choropleth Map Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Generates a choropleth map from a GeoDataFrame using the 'SIDR79' column, classified by Quantiles into 10 classes. The axes are turned off for a cleaner map display. ```python ax = gdf.plot(column="SIDR79", scheme="Quantiles", k=10, figsize=(16, 9)) ax.set_axis_off() ``` -------------------------------- ### Pinning Pooled Classifier to the first period Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Uses the bins from a Quantiles classifier calculated on the first column of data to initialize a Pooled classifier. ```python pinned = mapclassify.Pooled( data, classifier="UserDefined", bins=mapclassify.Quantiles(data[:, 0]).bins ) pinned ``` -------------------------------- ### Greedy coloring with 'smallest_last' networkx strategy Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Applies the 'smallest_last' coloring strategy, another option from networkx, using mapclassify.greedy. The resulting color assignments are plotted. ```python africa["greedy_s"] = greedy(africa, strategy="smallest_last") ax = africa.plot( "greedy_s", categorical=True, figsize=(8, 12), cmap="Set3", legend=True, edgecolor="w", ) ax.set_axis_off() ``` -------------------------------- ### Apply MaximumBreaks classifier Source: https://github.com/pysal/mapclassify/blob/main/notebooks/01_maximum_breaks.ipynb Initialize the MaximumBreaks classifier with a specified number of classes k. ```python mc.MaximumBreaks(y, k=4) ``` -------------------------------- ### Create Mapping for Legend Labels Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Generates a dictionary that maps integer class indices to their corresponding string representations obtained from get_legend_classes(), useful for custom legend creation. ```python mapping = {i: s for i, s in enumerate(q10.get_legend_classes())} mapping ``` -------------------------------- ### Define Strategies and Balanced Modes Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Defines lists of available strategies and balanced modes for map classification. ```python strategies = [ "balanced", "largest_first", "random_sequential", "smallest_last", "independent_set", "connected_sequential_bfs", "connected_sequential_dfs", "saturation_largest_first", ] balanced_modes = ["count", "area", "centroid", "distance"] ``` -------------------------------- ### Compare First Column Pooled Classifier with Unrestricted Quantiles Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Compares the first column's pooled classifier intervals and counts with an unrestricted Quantiles classifier applied to the same data subset. This highlights differences in classification when pooling is applied. ```python mapclassify.Quantiles(c0.y, k=4) ``` -------------------------------- ### Integrate mapclassify with GeoPandas Source: https://context7.com/pysal/mapclassify/llms.txt Demonstrates creating choropleth maps using mapclassify classifiers directly or via GeoPandas plot integration. ```python import mapclassify import geopandas as gpd import matplotlib.pyplot as plt from libpysal import examples # Load geographic data gdf = gpd.read_file(examples.get_path('columbus.shp')) # Create classifier q5 = mapclassify.Quantiles(gdf['CRIME'], k=5) # Use classifier's plot method fig, ax = q5.plot( gdf, cmap='OrRd', legend=True, title='Crime Rate by Quantiles', border_color='white', border_width=0.5 ) plt.show() # Or use geopandas with mapclassify scheme names fig, axes = plt.subplots(2, 2, figsize=(14, 12)) gdf.plot(column='CRIME', scheme='quantiles', k=5, ax=axes[0,0], legend=True, cmap='Reds') axes[0,0].set_title('Quantiles (k=5)') gdf.plot(column='CRIME', scheme='fisher_jenks', k=5, ax=axes[0,1], legend=True, cmap='Reds') axes[0,1].set_title('Fisher-Jenks (k=5)') gdf.plot(column='CRIME', scheme='natural_breaks', k=5, ax=axes[1,0], legend=True, cmap='Reds') axes[1,0].set_title('Natural Breaks (k=5)') gdf.plot(column='CRIME', scheme='equal_interval', k=5, ax=axes[1,1], legend=True, cmap='Reds') axes[1,1].set_title('Equal Interval (k=5)') plt.tight_layout() plt.show() ``` -------------------------------- ### Adjust transparency with revert_alpha Source: https://github.com/pysal/mapclassify/blob/main/notebooks/value_by_alpha.ipynb Use revert_alpha=True to make high y-values more transparent and low y-values more opaque. ```python # Create new figure fig, axs = plt.subplots(1, 2, figsize=(20, 10)) # create a vba_choropleth axs[0].set_title("revert_alpha = False") axs[0].set_axis_off() vba_choropleth( x, y, gdf, x_classification_kwds={"classifier": "quantiles"}, y_classification_kwds={"classifier": "quantiles"}, cmap="RdBu", ax=axs[0], revert_alpha=False, ) # set revert_alpha argument to True axs[1].set_title("revert_alpha = True") axs[1].set_axis_off() vba_choropleth( x, y, gdf, x_classification_kwds={"classifier": "quantiles"}, y_classification_kwds={"classifier": "quantiles"}, cmap="RdBu", ax=axs[1], revert_alpha=True, ) plt.show() ``` -------------------------------- ### Creating Value-by-Alpha Choropleths Source: https://github.com/pysal/mapclassify/blob/main/notebooks/value_by_alpha.ipynb Importing the vba_choropleth function and generating comparative plots with different transparency and divergence settings. ```python from mapclassify.value_by_alpha import vba_choropleth ``` ```python # Create new figure fig, axs = plt.subplots(2, 2, figsize=(15, 10)) # use gdf.plot() to create regular choropleth axs[0, 0].set_title("normal Choropleth") axs[0, 0].set_axis_off() gdf.plot(column=x, scheme="quantiles", cmap="RdBu", ax=axs[0, 0]) # use vba_choropleth to create Value-by-Alpha Choropleth axs[0, 1].set_title("Value-by-Alpha Choropleth") axs[0, 1].set_axis_off() vba_choropleth( x, y, gdf, x_classification_kwds={"classifier": "quantiles"}, y_classification_kwds={"classifier": "quantiles"}, cmap="RdBu", ax=axs[0, 1], ) # create a VBA Choropleth - divergent=False, revert_alpha=False axs[1, 0].set_title("divergent=False, revert_alpha=False") axs[1, 0].set_axis_off() vba_choropleth( x, y, gdf, x_classification_kwds={"classifier": "quantiles"}, y_classification_kwds={"classifier": "quantiles"}, cmap="RdBu", ax=axs[1, 0], divergent=True, revert_alpha=False, ) # create a VBA Choropleth - divergent=False, revert_alpha=True axs[1, 1].set_title("divergent=False, revert_alpha=True") axs[1, 1].set_axis_off() vba_choropleth( x, y, gdf, x_classification_kwds={"classifier": "quantiles"}, y_classification_kwds={"classifier": "quantiles"}, cmap="RdBu", ax=axs[1, 1], divergent=False, revert_alpha=True, ) plt.show() ``` -------------------------------- ### Quantiles Classification Source: https://github.com/pysal/mapclassify/blob/main/README.md Classify data using the Quantiles algorithm. ```python >>> mapclassify.Quantiles(y, k=5) ``` -------------------------------- ### Greedy Topological Coloring (Rook Adjacency) Source: https://context7.com/pysal/mapclassify/llms.txt Performs greedy topological coloring on African map data using rook adjacency (shared edges only). ```python from mapclassify import greedy import geopandas as gpd # Load geographic data world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[world.continent == 'Africa'].copy() africa = africa.to_crs('ESRI:102022') # Projected CRS for Africa # Use rook adjacency (shared edges only, not corners) africa['color_rook'] = greedy(africa, sw='rook') ``` -------------------------------- ### Visualize Strategy Results on Map Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Plots the classification results of each strategy on a map, with custom styling and legends. ```python plt_kws = {"categorical": True, "figsize": (16, 12), "cmap": "Set3", "legend": True} for strategy in times.index: ax = world.plot(strategy, **plt_kws) ax.set_axis_off() ax.set_title(strategy) ``` -------------------------------- ### Prepare RGBA Colors for Pydeck Source: https://github.com/pysal/mapclassify/blob/main/notebooks/08_manual_coloring.ipynb Convert color arrays into float-based lists to ensure compatibility with Pydeck's JSON serialization requirements. ```python import pydeck as pdk ``` ```python df["fill"] = pd.Series(list(colors.astype(float))).apply(list).values ``` ```python df["fill"] ``` -------------------------------- ### Apply classification schemes with classify() Source: https://context7.com/pysal/mapclassify/llms.txt Use the high-level classify() function to apply various schemes like quantiles, fisherjenks, boxplot, or user-defined bins with a single interface. ```python import mapclassify import numpy as np # Load example data (employment density in California counties) y = mapclassify.load_example() # Classify using quantiles (5 classes by default) quantiles = mapclassify.classify(y, 'quantiles') print(quantiles) # Quantiles # Interval Count # -------------------------- # [ 0.13, 1.46] | 12 # ( 1.46, 5.80] | 11 # ( 5.80, 13.28] | 12 # ( 13.28, 54.62] | 11 # ( 54.62, 4111.45] | 12 # Classify using Fisher-Jenks with 4 classes fj = mapclassify.classify(y, 'fisherjenks', k=4) print(f"Bins: {fj.bins}") print(f"Counts: {fj.counts.tolist()}") # Classify using box plot with custom hinge bp = mapclassify.classify(y, 'boxplot', hinge=2.0) print(f"IQR multiplier used: 2.0") print(f"Classes: {bp.k}") # User-defined bins custom = mapclassify.classify(y, 'userdefined', bins=[10, 50, 200, 1000]) print(custom) ``` -------------------------------- ### Plot Strategy Performance Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Generates a bar plot showing the performance (mean time elapsed) of each strategy on a logarithmic scale. ```python times = pandas.Series(times) ax = times.plot(kind="bar") ax.set_yscale("log") ``` -------------------------------- ### Use extended API Source: https://github.com/pysal/mapclassify/blob/main/notebooks/06_api.ipynb Perform classification using the extended classify function, which supports string-based scheme selection. ```python bp = mapclassify.classify(y, "box_plot") bp ``` ```python type(bp) ``` ```python q5 = mapclassify.classify(y, "quantiles", k=5) q5 ``` -------------------------------- ### Greedy Topological Coloring (Minimum Distance) Source: https://context7.com/pysal/mapclassify/llms.txt Performs greedy topological coloring on African map data, setting a minimum distance of 100,000 units between polygons of the same color. ```python from mapclassify import greedy import geopandas as gpd # Load geographic data world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[world.continent == 'Africa'].copy() africa = africa.to_crs('ESRI:102022') # Projected CRS for Africa # Set minimum distance between same colors africa['color_dist'] = greedy(africa, min_distance=100000) ``` -------------------------------- ### Greedy coloring with 'distance' balance strategy Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Applies a greedy coloring strategy that balances the distance between colors. The resulting color codes are plotted, utilizing the 'Set3' colormap and displaying a legend. ```python africa["greedy_distance"] = greedy(africa, strategy="balanced", balance="distance") ax = africa.plot( "greedy_distance", categorical=True, figsize=(8, 12), cmap="Set3", legend=True, edgecolor="w", ) ax.set_axis_off() ``` -------------------------------- ### Greedy Topological Coloring (Balanced by Area) Source: https://context7.com/pysal/mapclassify/llms.txt Performs greedy topological coloring on African map data, balancing colors by area instead of count. ```python from mapclassify import greedy import geopandas as gpd # Load geographic data world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[world.continent == 'Africa'].copy() africa = africa.to_crs('ESRI:102022') # Projected CRS for Africa # Balance by area instead of count africa['color_area'] = greedy(africa, strategy='balanced', balance='area') ``` -------------------------------- ### Map classification methods Source: https://github.com/pysal/mapclassify/blob/main/notebooks/03_choropleth.ipynb Dictionary mapping string keys to mapclassify classifier classes. ```python k_classifiers = { "equal_interval": mapclassify.EqualInterval, "fisher_jenks": mapclassify.FisherJenks, "jenks_caspall": mapclassify.JenksCaspall, "jenks_caspall_forced": mapclassify.JenksCaspallForced, "maximum_breaks": mapclassify.MaximumBreaks, "natural_breaks": mapclassify.NaturalBreaks, "quantiles": mapclassify.Quantiles, } ``` -------------------------------- ### Generate Polygon Lattice Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Helper function to create a grid of square polygons for testing adjacency. ```python def poly_lattice_gdf(dim, plot=False): polys = [] for x in range(dim): for y in range(dim): polys.append(Point(x, y).buffer(0.5, cap_style=3)) _gdf = geopandas.GeoDataFrame(geometry=polys) if plot: ax = _gdf.plot(edgecolor="w") ax.set_axis_off() return _gdf ``` -------------------------------- ### Apply Pooled Classification with k=4 Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Applies pooled classification with a specified number of classes (k=4). This allows for more control over the number of intervals in the classification. ```python res = mapclassify.Pooled(data, k=4) ``` -------------------------------- ### Pooled Classification with Quantiles Source: https://context7.com/pysal/mapclassify/llms.txt Applies pooled classification using the Quantiles classifier with k=5 to multi-temporal data, showing global and column-specific counts. ```python import mapclassify import numpy as np # Create multi-temporal data n = 20 data = np.array([np.arange(n) + i * n for i in range(1, 4)]).T print(f"Data shape: {data.shape}") # (20, 3) print(f"Column ranges: {data.min(axis=0)} to {data.max(axis=0)}") # Apply pooled classification pool = mapclassify.Pooled(data, classifier='Quantiles', k=5) # Global classifier applied to all data print(f"Global bins: {pooled.global_classifier.bins}") print(f"Global counts: {pooled.global_classifier.counts.tolist()}") # Same bins applied to each column for i, col_clf in enumerate(pooled.col_classifiers): print(f"Column {i} counts: {col_clf.counts.tolist()}") ``` -------------------------------- ### Display Synthetic Data Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Prints the generated synthetic data array to the console. The shape of the data is (20, 3), indicating 20 units and 3 time points. ```python data ``` -------------------------------- ### Create Value-by-Alpha Choropleth Source: https://context7.com/pysal/mapclassify/llms.txt Generates bivariate choropleths using color for one variable and transparency for another. Requires mapclassify, geopandas, and matplotlib. Can be configured with classification schemes and legends. ```python from mapclassify import vba_choropleth import geopandas as gpd import matplotlib.pyplot as plt # Load example data from libpysal import examples gdf = gpd.read_file(examples.get_path('columbus.shp')) # Basic VBA choropleth: color=HOVAL, alpha=CRIME fig, ax = vba_choropleth('HOVAL', 'CRIME', gdf, cmap='viridis') plt.title('Value-by-Alpha: HOVAL (color) by CRIME (alpha)') plt.show() ``` ```python fig, ax = plt.subplots(figsize=(12, 8)) vba_choropleth( 'HOVAL', 'CRIME', gdf, cmap='RdBu', ax=ax, x_classification_kwds={'classifier': 'quantiles', 'k': 5}, y_classification_kwds={'classifier': 'quantiles', 'k': 5}, legend=True, legend_kwargs={'x_label': 'Home Value', 'y_label': 'Crime Rate'} ) plt.show() ``` ```python fig, ax = vba_choropleth( 'HOVAL', 'CRIME', gdf, divergent=True, revert_alpha=True, min_alpha=0.3 ) plt.show() ``` -------------------------------- ### Default greedy coloring Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Applies the default greedy coloring strategy to the GeoDataFrame and displays the first 5 results. This strategy aims to balance the number of features per color. ```python africa["greedy_default"] = greedy(africa) africa["greedy_default"].head(5) ``` -------------------------------- ### Generate Synthetic Longitudinal Data Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Creates a synthetic dataset with 20 cross-sectional units over three time points, where the mean of the series increases over time. This data is suitable for demonstrating pooled classification. ```python n = 20 data = numpy.array([numpy.arange(n) + i * n for i in range(1, 4)]).T data.shape ``` -------------------------------- ### Inspect classifier object Source: https://github.com/pysal/mapclassify/blob/main/notebooks/02_legends.ipynb Display the classifier object to verify that formatting changes are not applied to the object state unless explicitly set. ```python q6 ``` -------------------------------- ### Compare Last Column Pooled Classifier with Unrestricted Quantiles Source: https://github.com/pysal/mapclassify/blob/main/notebooks/04_pooled.ipynb Compares the last column's pooled classifier with an unrestricted Quantiles classifier applied to its data. This demonstrates how pooling affects classification compared to individual column classification. ```python mapclassify.Quantiles(c2.y, k=4) ``` -------------------------------- ### Benchmark classification methods across different polygon counts Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Iterates through various numbers of polygons, generates a GeoDataFrame for each, and benchmarks the defined classification methods using the 'run_greedy' function. Results are printed and stored in a pandas DataFrame. ```python times = pandas.DataFrame(index=params.keys()) steps = range(10, 110, 10) for step in steps: print(step, "----------------------------------------------") gdf = poly_lattice_gdf(step, plot=False) for method, kwargs in params.items(): mean_time, colors = run_greedy(gdf, kwargs, min_colors=2) printer(method, mean_time, numpy.max(colors)) times.loc[method, step] = mean_time ``` -------------------------------- ### Legendgram with specified colormap Source: https://github.com/pysal/mapclassify/blob/main/notebooks/09_legendgram.ipynb Plots a map using the 'plasma' colormap and the Quantiles scheme, then overlays a legendgram with specified size, location, and clipping range. ```python ax = gdf.plot("GI89", cmap="plasma", scheme="Quantiles") ax.axis("off") classifier = mapclassify.Quantiles(gdf["GI89"]) hax = classifier.plot_legendgram( ax=ax, legend_size=("15%", "30%"), loc="lower right", clip=(0.3, 0.4), ) ``` -------------------------------- ### List Available Classifiers in Mapclassify Source: https://github.com/pysal/mapclassify/blob/main/notebooks/01_maximum_breaks.ipynb Access the list of all available classifier names within the mapclassify library. This can be useful for understanding the range of classification methods provided. ```python mc.classifiers.CLASSIFIERS ``` -------------------------------- ### Greedy coloring with 'area' balance strategy Source: https://github.com/pysal/mapclassify/blob/main/notebooks/05_Greedy_coloring.ipynb Applies a greedy coloring strategy that balances the area covered by each color. The resulting color codes are plotted using the 'Set3' colormap. ```python africa["greedy_area"] = greedy(africa, strategy="balanced", balance="area") ax = africa.plot( "greedy_area", categorical=True, figsize=(8, 12), cmap="Set3", legend=True, edgecolor="w", ) ax.set_axis_off() ``` -------------------------------- ### Legendgram with clipping and different scheme Source: https://github.com/pysal/mapclassify/blob/main/notebooks/09_legendgram.ipynb Plots a map using the Quantiles scheme and overlays a legendgram. The display is clipped to a smaller range, and vertical lines are added. ```python ax = gdf.plot("GI89", scheme="Quantiles") ax.axis("off") classifier = mapclassify.Quantiles(gdf["GI89"]) hax = classifier.plot_legendgram( ax=ax, legend_size=("50%", "12%"), loc="lower left", clip=(0.3, 0.5), vlines=True, ) ```