mapclassify: Classification Schemes for Choropleth Maps

repository·main·Indexed 40 days ago

https://github.com/pysal/mapclassify

A Python library within the PySAL ecosystem for implementing classification schemes used in choropleth maps. It provides tools to determine the number of classes and assign observations to them, featuring a streamlined `classify()` function and support for schemes such as Quantiles, EqualInterval, FisherJenks, NaturalBreaks, and BoxPlot. Designed for use with mapping tools like GeoPandas, it includes utilities for rolling classifications in Pandas DataFrames and colormap adjustments via the `value_by_alpha` module.

Tokens
16.6K
Snippets
64
Records
77
Agent score
99%

What's inside mapclassify

  1. Overview of mapclassify

    main
    mapclassify is an open-source Python library designed for Choropleth map classification. It is a component of the PySAL (Python Spatial Analysis Library) ecosystem. The library provides various classification schemes (such as Equal Interval, Quantiles, and Fisher Jenks) used to group data values into classes for thematic mapping.
  2. Use mapclassify classifiers for choropleth maps

    main

    The mapclassify package provides various classification schemes used to group data into classes for choropleth maps. You can instantiate specific classifier classes by passing a sequence of values (like a list, NumPy array, or Pandas Series) and the desired number of classes (k).

    Supported classifier classes include:

    • BoxPlot
    • EqualInterval
    • FisherJenks
    • FisherJenksSampled
    • greedy
    • HeadTailBreaks
    • JenksCaspall
    • JenksCaspallForced
    • JenksCaspallSampled
    • MaxP
    • MaximumBreaks
    • NaturalBreaks
    • Percentiles
    • PrettyBreaks
    • Quantiles
    • StdMean
    • UserDefined
  3. Access the calemp dataset

    main

    The calemp dataset contains employment density data for California counties. It consists of polygon data for 58 counties and is intended for use with 11 classification classes (k=11). The dataset includes calempdensity.csv, which provides the employment and employment density values.

    Dataset Metadata:

    • Content: Employment and employment density in California counties.
    • Geometry: Polygon data.
    • Sample Size (n): 58
    • Classification Classes (k): 11
    • Source: Anselin, L. and S.J. Rey (in progress) Spatial Econometrics: Foundations.
  4. Quickstart with mapclassify example data

    main

    To get started, you can load the built-in example dataset which contains employment density data for 58 California counties. This is useful for testing various classification schemes.

    import mapclassify
    y = mapclassify.load_example()
    print(y.mean())
    print(y.min(), y.max())
    import mapclassify
    y = mapclassify.load_example()
    y.mean()
    y.min(), y.max()
  5. Install the released version of mapclassify

    main

    You can install the stable version of mapclassify using either conda or pip. Ensure you are using Python 3.12 or newer.

    # Using conda via the conda-forge channel
    conda install -c conda-forge mapclassify
    
    # Using pip
    pip install -U mapclassify
  6. Set up a local development environment

    main

    To develop mapclassify locally, you should use a conda environment and install the package in editable mode. This is necessary because geopandas (used in development) depends on a stable version of mapclassify.

    conda-env create -f environment.yml
    conda activate mapclassify
    conda remove -n mapclassify mapclassify
    pip install -e .
    conda-env create -f environment.yml
    conda activate mapclassify
    conda remove -n mapclassify mapclassify
    pip install -e .
  7. Understand the MapClassifier base class

    main

    The MapClassifier is the abstract base class for all classification schemes in mapclassify. A classifier takes an array of $n$ values and assigns each value to one of $k$ mutually exclusive and exhaustive classes.

    Key properties and methods available on all classifier instances:

    • y: The original input data array.
    • bins: The calculated class breaks/edges.
    • counts: The number of observations in each bin.
    • classes: A list of lists containing the indices of observations belonging to each class.
    • find_bin(x): Returns the bin index for input values x. Unlike numpy.digitize, this method ensures data outside the min/max range is assigned to the nearest available bin.
    • update(y, inplace=False, **kwargs): Adds new data or changes classification parameters. If inplace=False, it returns a new classifier instance.
    • table(): Returns a formatted tabular report of the classification results.
    • get_gadf(): Returns the 'Goodness of Absolute Deviation of Fit'.
  8. Use the Pooled classifier for longitudinal data

    main

    The mapclassify.Pooled classifier is designed for longitudinal spatial data where you want to apply the same classification scheme across different time periods. Instead of calculating unique breaks for each period, Pooled treats the entire data matrix as a single collection to determine class breaks, ensuring that the class definitions remain constant across all periods. This allows you to observe how the distribution of values shifts between classes over time.

    When using Pooled, you can access:

    • res.global_classifier: The classifier calculated from the entire pooled dataset.
    • res.col_classifiers: A list of classifiers, one for each column (period) in the input data, using the global breaks.
    import numpy
    import mapclassify
    
    # data should be a 2D array where columns represent time periods
    res = mapclassify.Pooled(data, k=4)
    
    # Access the classifier for the first period
    c0 = res.col_classifiers[0]
    
    # Access the global classifier used for all periods
    global_res = res.global_classifier
  9. Robustness of the scheme argument in classify()

    main

    The scheme argument in mapclassify.classify() is case-insensitive and flexible regarding underscores and capitalization. The following variations are functionally equivalent for the Box Plot scheme:

    • "box_plot"
    • "boxPlot"
    • "Boxplot"
    • "Box_plot"

    This robustness allows for more flexible string inputs when programmatically selecting schemes.

    # All these calls work for the same scheme
    mapclassify.classify(y, "boxPlot")
    mapclassify.classify(y, "Boxplot")
    mapclassify.classify(y, "Box_plot")
  10. Create choropleth maps with GeoPandas and mapclassify

    main

    While mapclassify handles the mathematical classification of data, it is designed to work alongside visualization libraries like geopandas and matplotlib to render maps.

    You can use a classification scheme directly within a GeoDataFrame's .plot() method by specifying the scheme and k (number of classes) arguments. Alternatively, you can create a standalone classifier object and use its bin assignments to create a new column in your GeoDataFrame for more control over the visualization.

    import geopandas
    import mapclassify
    import matplotlib.pyplot as plt
    
    # Method 1: Direct plotting via GeoPandas
    ax = gdf.plot(column="SIDR79", scheme="Quantiles", k=10, figsize=(16, 9))
    ax.set_axis_off()
    
    # Method 2: Manual classification for more control
    q10 = mapclassify.Quantiles(gdf.SIDR79, k=10)
    # Use q10.yb (y-bins) to assign class indices to a new column
    ax = gdf.assign(cl=q10.yb).plot(
        column="cl",
        categorical=True,
        k=10,
        cmap="OrRd",
        legend=True
    )