Search code examples
pythonaltairvega-litevega

Mask values in Python Altair heatmap plots


I'd like to plot a heatmap with masked values using Altair. This can be done via passing a mask array to seaborn's heatmap method, but I want to do it using Altair. Thanks!

Desired heatmap with masked values


Solution

  • In Altair, you can apply a mask by removing fro the dataset any data that you don't want to be shown. For example, here is a masked version of the Simple Heatmap example from Altair's documentation:

    import altair as alt
    import numpy as np
    import pandas as pd
    
    # Compute x^2 + y^2 across a 2D grid
    x, y = np.meshgrid(range(-5, 5), range(-5, 5))
    z = x ** 2 + y ** 2
    
    # Convert this grid to columnar data expected by Altair
    source = pd.DataFrame({'x': x.ravel(),
                           'y': y.ravel(),
                           'z': z.ravel()})
    
    mask = np.random.rand(len(source)) < 0.9
    
    alt.Chart(source.iloc[mask]).mark_rect().encode(
        x='x:O',
        y='y:O',
        color='z:Q'
    )
    

    enter image description here

    If you want the masking to take place via the chart specification rather than via a preprocessing step, you can similarly filter rows using a Filter transform.