Skip to content

Grid Operations

This page documents functions and utilities for working with geographic grids in GeoFacetMakie.jl.

Grid Loading Functions

GeoFacetMakie.load_grid_from_csv Function
julia
load_grid_from_csv(filename::String, directory::String) -> StructArray{GridEntry}

Load a geographical grid from a CSV file in geofacet format.

The CSV file should have columns: row, col, and a code column (case-insensitive), and optionally name

  • row: Grid row position (integer)

  • col: Grid column position (integer)

  • code/Code/CODE: Region identifier/abbreviation (string) - column name must contain "code"

  • name: Full region name (string, optional - defaults to code if missing)

  • Additional columns will be stored as metadata in each GridEntry

Arguments

  • filename::String: Name of the CSV file (with or without .csv extension)

  • directory::String: Directory containing the CSV file

Returns

  • StructArray{GridEntry}: A GeoGrid (StructArray) containing the loaded grid data with region codes, positions, display names, and any additional metadata from the CSV

Example

julia
# Load from custom directory
grid = load_grid_from_csv("us_state_grid1.csv", "/path/to/grids")

# Load from package data directory
grids_dir = joinpath(pkgdir(GeoFacetMakie), "src", "data", "grids")
grid = load_grid_from_csv("us_state_grid1", grids_dir)
source
julia
load_grid_from_csv(filename::String) -> StructArray{GridEntry}

Load a geographical grid from the package's default grids directory.

Arguments

  • filename::String: Name of the CSV file (with or without .csv extension)

Returns

  • StructArray{GridEntry}: A GeoGrid (StructArray) containing the loaded grid data

Example

julia
# Load from package default directory
grid = load_grid_from_csv("us_state_grid1")
grid = load_grid_from_csv("eu_grid1.csv")
source
GeoFacetMakie.list_available_grids Function
julia
list_available_grids() -> Vector{String}

List all available predefined grid layouts.

Returns

  • Vector{String}: Names of available grid files

Example

julia
grids = list_available_grids()
println("Available grids:

", join(grids, "
"))
source

Grid Utility Functions

GeoFacetMakie.grid_dimensions Function
julia
grid_dimensions(grid::GeoGrid) -> Tuple{Int, Int}

Get the dimensions of a grid as (max_row, max_col). Returns (0, 0) for empty grids.

source
GeoFacetMakie.validate_grid Function
julia
validate_grid(grid::GeoGrid) -> Bool

Validate that no two regions occupy the same position. Returns true if valid, throws ArgumentError if conflicts exist.

source
GeoFacetMakie.has_region Function
julia
has_region(grid::GeoGrid, region::String) -> Bool

Check if a region exists in the grid.

source
GeoFacetMakie.get_position Function
julia
get_position(grid::GeoGrid, region::String) -> Union{Tuple{Int, Int}, Nothing}

Get the position of a region in the grid. Returns nothing if the region doesn't exist.

source
GeoFacetMakie.get_region_at Function
julia
get_region_at(grid::GeoGrid, row::Int, col::Int) -> Union{String, Nothing}

Get the region name at a specific grid position. Returns nothing if no region exists at that position.

source
GeoFacetMakie.get_regions Function
julia
get_regions(grid::GeoGrid) -> Vector{String}

Get all region names in the grid.

source
GeoFacetMakie.is_complete_rectangle Function
julia
is_complete_rectangle(grid::GeoGrid) -> Bool

Check if the grid forms a complete rectangle (no missing cells).

source

Neighbor Detection Functions

GeoFacetMakie.has_neighbor_below Function
julia
has_neighbor_below(grid::GeoGrid, region::String) -> Bool

Check if a region has any neighboring region below it in the same column. Returns false if the region doesn't exist in the grid.

source
GeoFacetMakie.has_neighbor_left Function
julia
has_neighbor_left(grid::GeoGrid, region::String) -> Bool

Check if a region has any neighboring region to its left in the same row. Returns false if the region doesn't exist in the grid.

source
GeoFacetMakie.has_neighbor_right Function
julia
has_neighbor_right(grid::GeoGrid, region::String) -> Bool

Check if a region has any neighboring region to its right in the same row. Returns false if the region doesn't exist in the grid.

source
GeoFacetMakie.has_neighbor_above Function
julia
has_neighbor_above(grid::GeoGrid, region::String) -> Bool

Check if a region has any neighboring region above it in the same column. Returns false if the region doesn't exist in the grid.

source

Predefined Grids

GeoFacetMakie.get_predefined_grids_count Function
julia
get_predefined_grids_count() -> Int

Get the number of predefined grid constants that were created.

Returns

  • Int: Number of predefined grid constants available

Example

julia
count = get_predefined_grids_count()
println("Available predefined grids: ", count)
source

Grid Structure

Grid Format

Geographic grids are StructArrays with a specific structure:

julia
# Create a simple grid
grid = GeoGrid(
    ["CA", "TX", "NY"],     # Region identifiers
    [2, 3, 1],              # Grid row positions
    [1, 2, 3]               # Grid column positions
)

Required Fields

  • region: Unique identifiers for geographic regions (String)

  • row: Grid row positions, starting from 1 (Integer)

  • col: Grid column positions, starting from 1 (Integer)

  • name: Display names for regions (String, defaults to region)

  • metadata: Additional metadata (Dict{String,Any})

Built-in Grids

Available Grids

GeoFacetMakie.jl includes many pre-defined grids from the geofacet collection:

julia
# List all available grids
available = list_available_grids()
println("Available grids: ", join(available[1:5], ", "), "...")

# Load a specific grid
grid = load_grid_from_csv("us_state_grid1")

Common US State Grids

Several US state grid layouts are commonly used:

  • us_state_grid1: Standard US state layout with Alaska and Hawaii positioned in the lower left

  • us_state_grid2: Alternative arrangement with different positioning for western states

  • us_state_grid3: Compact layout optimizing for space efficiency

  • us_state_contiguous_grid1: Contiguous US states only (excludes Alaska and Hawaii)

Grid Comparison

GridStatesAlaska/HawaiiAspect RatioBest For
us_state_grid150 + DCLower leftWideGeneral use
us_state_grid250 + DCAlternativeMediumPresentations
us_state_grid350 + DCCompactSquareSmall figures
us_state_contiguous_grid148ExcludedWideContinental focus

Creating Custom Grids

Basic Custom Grid

julia
# Simple custom grid using GeoGrid constructor
my_grid = GeoGrid(
    ["A", "B", "C", "D"],
    [1, 1, 2, 2],
    [1, 2, 1, 2]
)

Geographic Custom Grid

julia
# European countries grid with names
europe_grid = GeoGrid(
    ["UK", "FR", "DE", "IT", "ES"],
    [1, 2, 2, 3, 3],
    [1, 1, 2, 2, 1],
    ["United Kingdom", "France", "Germany", "Italy", "Spain"]
)

Programmatic Grid Generation

julia
function create_rectangular_grid(regions::Vector{String}, ncols::Int)
    nrows = ceil(Int, length(regions) / ncols)

    rows = Int[]
    cols = Int[]

    for (i, region) in enumerate(regions)
        row = ceil(Int, i / ncols)
        col = mod1(i, ncols)
        push!(rows, row)
        push!(cols, col)
    end

    return GeoGrid(regions, rows, cols)
end

# Generate 3-column grid for any regions
regions = ["R1", "R2", "R3", "R4", "R5"]
auto_grid = create_rectangular_grid(regions, 3)

Grid Design Principles

Geographic Accuracy vs Readability

Balance between maintaining geographic relationships and creating readable layouts:

julia
# Geographically accurate (may be hard to read)
accurate_grid = GeoGrid(
    ["FL", "GA", "SC", "NC"],
    [4, 3, 2, 1],  # True north-south order
    [1, 1, 1, 1]   # All in same column
)

# Readable compromise (sacrifices some accuracy)
readable_grid = GeoGrid(
    ["FL", "GA", "SC", "NC"],
    [2, 2, 1, 1],  # Compressed vertically
    [1, 2, 1, 2]   # Spread horizontally
)

Handling Special Cases

Irregular Geographies

julia
# Grid with gaps for irregular shapes
irregular_grid = GeoGrid(
    ["AK", "HI", "CA", "OR", "WA"],
    [1, 4, 3, 2, 1],     # Alaska and Hawaii separate
    [1, 1, 2, 2, 2]      # Gaps in layout
)

Grid File Operations

Saving and Loading

julia
# Load from package grids
grid = load_grid_from_csv("us_state_grid1")

# Load from custom directory
custom_grid = load_grid_from_csv("my_grid.csv", "/path/to/grids")

# Validate after loading
validate_grid(grid)  # Returns true if valid, throws error if conflicts

Grid Formats

CSV Format

csv
code,name,row,col
CA,California,3,1
OR,Oregon,2,1
WA,Washington,1,1

The CSV loader supports various column name conventions:

  • code, code_alpha3, code_country, code_iso_3166_2 for region identifiers

  • name for display names (optional)

  • row, col for positions (required)

  • Additional columns become metadata

Troubleshooting Grids

Common Issues

Duplicate positions:

julia
# Problem: Two regions at same position
# Solution: Use validate_grid to check
try
    validate_grid(grid)
    println("Grid is valid")
catch e
    println("Grid validation failed: ", e)
end

Missing regions:

julia
# Problem: Data regions not in grid
# Solution: Check which regions are available
data_regions = unique(data.state)
grid_regions = get_regions(grid)
missing = setdiff(data_regions, grid_regions)
println("Missing regions: ", missing)

Sparse grids:

julia
# Problem: Grid has many empty spaces
# Solution: Check grid density
max_row, max_col = grid_dimensions(grid)
density = length(grid) / (max_row * max_col)
if density < 0.3
    @warn "Grid is very sparse ($(round(density*100))% filled)"
end

Best Practices

1. Start with Built-ins

Use existing grids when possible, customize only when needed.

2. Validate Early and Often

Always validate grids before using with real data.

3. Test with Sample Data

Create sample data to test grid layouts.

4. Document Custom Grids

Include metadata about grid design decisions.

5. Consider Your Audience

Prioritize readability over perfect geographic accuracy.

See Also