Altair heatmap ticks text

693 views Asked by At

Is there a way to set the ticks text to a list of strings? I know that ideally it is best to have the ticks directly in the dataset but unfortunately this is not always possible or practical.

I am working on a heatmap and I want to be able to set the ticks values to be shown and then place specific strings at those positions.

Here is a minimal example in which I have set ticks values at 2pi on the x-axis.

# Compute x^2 + y^2 across a 2D grid
x, y = np.meshgrid([i*np.pi for i in range(10)], [i*np.pi for i in range(10)])
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()})

alt.Chart(source).mark_rect().encode(
    alt.X('x:O', axis=alt.Axis(values=[2*i*np.pi for i in range(5)], format=".2f")),
    alt.Y('y:O', axis=alt.Axis(format=".2f")),
    color='z:Q'
)

enter image description here

1

There are 1 answers

1
jakevdp On BEST ANSWER

One way to do this is to use the labelExpr axis attribute, which allows defining new label values using the Vega Expression syntax. For example:

alt.Chart(source).mark_rect().encode(
    alt.X('x:O',
      axis=alt.Axis(
        values=[2*i*np.pi for i in range(5)],
        labelExpr="round(datum.value / PI) + 'π'"
      )
    ),
    alt.Y('y:O',
      axis=alt.Axis(
        labelExpr="round(datum.value / PI) + 'π'"
      )
    ),
    color='z:Q'
)

enter image description here